Reputation:
I have this variable:
var search = "dummy";
var replace = "<strong>" + search + "</strong>";
var contents = "my contents are here and this dummy value should be bolded...";
contents.replace(/search/gi, replace);
So, How can I set this "search" variable under my RegEx pattern, followed with /gi settings for my match.
Upvotes: 0
Views: 829
Reputation: 42140
You can use backreferences: The $1 is remembering what you matched with the regular expression. It does this because the word you are searching for is placed inside round brackets which form a capturing group.
var contents = "my contents are here and this dummy value should be bolded...";
function makeStronger( word, str ) {
var rxp = new RegExp( '(' + word +')', 'gi' );
return str.replace( rxp, '<strong>$1<\/strong>' );
}
console.log( makeStronger( 'dummy', contents ) );
// my contents are here and this <strong>dummy</strong> value should be bolded...
Upvotes: 1
Reputation: 34978
You can also create a regular expression using the RegExp object:
search = "dummy";
x = new RegExp(search,"gi");
var search = "dummy";
var replace = "<strong>" + search + "</strong>";
var contents = "my contents are here and this dummy value should be bolded...";
window.alert(contents.replace(x, replace));
Upvotes: 3
Reputation: 2657
try
new RegExp('yourSearchHere', 'gi');
you should also be aware of the fact, that you have to escape certain sequences. Btw. you have to double escape these when you're constructing a regex like this (new RegExp('\\n') -> matches \n)
Upvotes: 4