Regular expression syntax error

I am creating a regular expression dynamically.

var link = "www.google.com"; var reg = '^'+link+'{1}|(?<=\s)'+link+'{1}(?=\s)|'+link+'{1}$'; console.log(reg); var result = new RegExp(reg, 'g'); 

I get this error

 Uncaught SyntaxError: Invalid regular expression: /^www.google.com{1}|(?<=s)www.google.com{1}(?=s)|www.google.com{1}$/: Invalid group 

Here is the generated regular expression:

^www.google.com{1}|(?<=s)www.google.com{1}(?=s)|www.google.com{1}$

+6
source share
2 answers

JavaScript regex engine does not support appearance. Another thing: you must double the escape \ inside the RegExp constructor.

What you are trying to achieve is to make the URL match the word boundaries.

Try using

 RegExp.escape= function(s) { return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); }; var reg = '\\b'+RegExp.escape(link)+'\\b'; 

code:

 RegExp.escape= function(s) { return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); }; var link = "www.google.com" var reg = '\\b'+RegExp.escape(link)+'\\b'; alert(new RegExp(reg, "g")); 

Note I am adding RegExp.Escape to avoid special characters in the arguments passed to the RegExp constructor ( RegExp.Escape . Must be \\. ).

+5
source

JavaScript does not support lookbehind groups.

In addition, your regular expression is created from strings. You must make sure that the regular expression metacharacters "survive" in the process of parsing the string, and in particular, your \s must be expressed as \\s .

Please note that the characters . in the URL of your pattern will be interpreted as the "wildcard" character of the regular expression, unless you also put \\ in front of it.

Finally, it is not clear what you expect from these {1} things; in JavaScript, which will match the sequence of characters {1} .

+1
source

Source: https://habr.com/ru/post/987582/


All Articles