JavaScript regex engine did not support look-behinds at all before ECMAScript 2018 was released.(JavaScript的正则表达式引擎根本不支持查找屁股的ECMAScript 2018发布之前。)
Now, if you use this in Chrome, it will not throw any error now:(现在,如果您在Chrome中使用此功能,它将不会引发任何错误:)
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.(另一件事:您必须在RegExp构造函数中加倍转义\
。)
What you are trying to acheive is to make the URL match at word boundaries.(您要达到的目的是使URL在单词边界处匹配。)
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 (eg .
must be \\.
).(注意,我正在添加RegExp.Escape
以便在传递给RegExp
构造函数的参数中转义特殊字符(例如.
必须为\\.
)。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…