简体   繁体   中英

JavaScript RegEx: How to create a RegEx pattern using a specific value from a Variable?

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.

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)

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/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM