0

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.

0

3 Answers 3

4

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)

Sign up to request clarification or add additional context in comments.

1 Comment

this would fail if we have input as \\\
3

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));

http://jsfiddle.net/YhqjY/

Comments

1

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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.