I am creating a regex 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 am getting 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 regex:
^www.google.com{1}|(?<=s)www.google.com{1}(?=s)|www.google.com{1}$
JavaScript regex engine did not support look-behinds at all before ECMAScript 2018 was released.
Now, if you use this in Chrome, it will not throw any error now:
var link = "www.google.com";
var reg = '^'+link+'{1}|(?<=\s)'+link+'{1}(?=\s)|'+link+'{1}$';
console.log(reg);
var result = new RegExp(reg, 'g');
Another thing: you must double escape \
inside RegExp constructor.
What you are trying to acheive is to make the URL match at 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 the RegExp.Escape
in order to escape special characters in the arguments passed to the RegExp
constructor (e.g. .
must be \\.
).
JavaScript does not support lookbehind groups.
On top of that, your regular expression is being built up from strings. You have to make sure that your regular expression metacharacters "survive" the process of string constant parsing, and in particular your \s
needs to be expressed as \\s
.
Note also that the .
characters in the URL portion of your pattern will be interpreted as the regex "wildcard" symbol if you don't precede them with \\
as well.
Finally, it's not clear what you expect those {1}
things to do; in JavaScript that will match the sequence of characters {1}
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With