Skip to content

Instantly share code, notes, and snippets.

@bettysteger
Last active August 29, 2015 14:27
Show Gist options
  • Save bettysteger/06a8feb10f20345b31d7 to your computer and use it in GitHub Desktop.
Save bettysteger/06a8feb10f20345b31d7 to your computer and use it in GitHub Desktop.
How to reuse matched value of regex in replace JS function
var text = "this is a {highlighted} text";
var regex = /\{\S+?\}/g;
var html = text.replace(regex, '<mark>$&</mark>'); // $& = matched value = {highlight}
alert(html); // => "this is a <mark>{highlighted}</mark> text"
var regex2 = /\{(\S+?)\}/g; // you need ()-brackets to get $1
var html2 = text.replace(regex2, '<mark>$1</mark>'); // $1 = first () = highlight
alert(html2); // => "this is a <mark>highlighted</mark> text"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment