Use Dynamic (Variable) String as Regex Pattern in JavaScript

Javascript Regexp dynamic generation from variables?

You have to use RegExp:

str.match(new RegExp(pattern1+'|'+pattern2, 'gi'));

When I'm concatenating strings, all slashes are gone.

If you have a backslash in your pattern to escape a special regex character, (like \(), you have to use two backslashes in the string (because \ is the escape character in a string): new RegExp('\\(') would be the same as /\(/.

So your patterns have to become:

var pattern1 = ':\\(|:=\\(|:-\\(';
var pattern2 = ':\\(|:=\\(|:-\\(|:\\(|:=\\(|:-\\(';

Use dynamic (variable) string as regex pattern in JavaScript

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.

How do you use a variable in a regular expression?

Instead of using the /regex\d/g syntax, you can construct a new RegExp object:

var replace = "regex\\d";
var re = new RegExp(replace,"g");

You can dynamically create regex objects this way. Then you will do:

"mystring1".replace(re, "newstring");

Dynamic String Matching

Couple of things you have to change:

  • For dynamic pattern use RegExp
  • over Vs Over is another thing. Make it case insensitive by using i

Here is your modified code:

// With RegExp, case insensitivefunction matchString1(str, match) {    let result = str.match(new RegExp(match, 'ig'));    console.log('Output: ' + result);}// With RegExp, case insensitivefunction matchString2(str, match, para) {    let result = str.match(new RegExp(match, para));    console.log('Output: ' + result);}// Without RegExp, case sensitivefunction matchString3(str, match) {    let result = str.match(match);    console.log('Output: ' + result);}
matchString1('Hello Stack Overflow', 'over');matchString2('Hello Stack Overflow', 'over', 'ig');matchString3('Hello Stack Overflow', 'Over');

JS Regex dynamic generation from variables

Create the regular expression pattern in a variable and then use new RegExp() with that variable that has the pattern. And don't use g as a part of the pattern, pass it as a second argument of RegExp() instead.

var string = "How are you doing today? You are such a nice person!";var text = 'are';var regEx = '\\b'+text+'\\b';var count =  string.match(new RegExp(regEx,"g")).length;alert(count);

Use dynamic (variable) string as regex pattern in dart

A generic function to escape any literal string that you want to put inside a regex as a literal pattern part may look like

escape(String s) {
return s.replaceAllMapped(RegExp(r'[.*+?^${}()|[\]\\]'), (x) {return "\\${x[0]}";});
}

It is necessary because an unescaped special regex metacharacter either causes a regex compilation error (like mismatched ( or )) or may make the pattern match something unexpected. See more details about escaping strings for regex at MDN.

So, if you have myfile.png, the output of escape('myfile.png') will be myfile\.png and the . will only match literal dot char now.

In the current scenario, you do not have to use this function because max and min thresholds are expressed with digits and digits are no special regex metacharacters.

You may just use

betweenLenth(val, field, [min = 4, max = 20]) {
final RegExp nameExp = new RegExp("^\\w{$min,$max}\$");
if (!nameExp.hasMatch(val))
return field + " must be between $min - $max characters ";
return "Correct!";
}

The resulting regex is ^\w{4,20}$.

Note:

  • Use non-raw string literals in order to use string interpolation
  • Escape the end of string anchor in regular string literals to define a literal $ char
  • Use double backslashes to define regex escape sequences ("\\d" to match digits, etc.)

How to use a variable inside a RegEx pattern?

Use new RegExp(string) to build a regular expression dynamically. The literal /../ form cannot be used with dynamic content.

Make sure to have a valid pattern after building the string.

var len = 99;
var re = new RegExp(".(?=.{" + len + "})", "g");
var output = input.replace(re, "*")

Also see (and vote for dupe of):

  • How do you use a variable in a regular expression?


Related Topics



Leave a reply



Submit