Skip to content
Advertisement

Use dynamic (variable) string as regex pattern in JavaScript

I want to add a (variable) tag to values with regex, the pattern works fine with PHP but I have troubles implementing it into JavaScript.

The pattern is (value is the variable):

/(?!(?:[^<]+>|[^>]+</a>))b(value)b/is

I escaped the backslashes:

var str = $("#div").html();
var regex = "/(?!(?:[^<]+>|[^>]+<\/a>))\b(" + value + ")\b/is";
$("#div").html(str.replace(regex, "<a href='#" + value +">" + value + "</a>"));

But this seem not to be right, I logged the pattern and its exactly what it should be. Any ideas?

Advertisement

Answer

To create the regex from a string, you have to use JavaScript’s RegExp object.

If you also want to match/replace more than one time, then you must add the g (global match) flag. Here’s an example:

var stringToGoIntoTheRegex = "abc";
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;

var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.

JSFiddle demo here.


In the general case, escape the string before using as regex:

Not every string is a valid regex, though: there are some speciall characters, like ( or [. To work around this issue, simply escape the string before turning it into a regex. A utility function for that goes in the sample below:

function escapeRegExp(stringToGoIntoTheRegex) {
    return stringToGoIntoTheRegex.replace(/[-/\^$*+?.()|[]{}]/g, '\$&');
}

var stringToGoIntoTheRegex = escapeRegExp("abc"); // this is the only change from above
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;

var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.

JSFiddle demo here.



Note: the regex in the question uses the s modifier, which didn’t exist at the time of the question, but does exist — a s (dotall) flag/modifier in JavaScript — today.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement