Last active
August 29, 2015 14:27
-
-
Save bettysteger/06a8feb10f20345b31d7 to your computer and use it in GitHub Desktop.
How to reuse matched value of regex in replace JS function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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