简体   繁体   English

如果搜索包含括号或方括号,则RegEx匹配返回未定义

[英]RegEx matching returns undefined if the search includes parenthesis or square brackets

I have a script that is more or less used like this: 我有一个或多或少像这样使用的脚本:

 var $pencilers = { '\\\\(signed\\\\)': '(assinado)', 'pencils': 'arte', '\\\\[as ': '[como ' }; var $pencils = 'Al Williamson [as AW] (signed)' var pen = new RegExp(Object.keys($pencilers).join("|"),"g"); $pencils = $pencils.replace(pen, function(matched){ return $pencilers[matched]; }); console.log($pencils) // $pencils returns: Al Williamson undefinedA. W.] undefined 

Can't figure out why does it returns undefined. 无法弄清楚为什么它返回未定义。

When I test it in Regex101 it works perfectly. 当我在Regex101中对其进行测试时,它可以完美运行。 Can anyone help out? 有人可以帮忙吗?

If you did a console.log(matched) , you'd notice that your matches don't match the object keys. 如果您做了console.log(matched) ,您会发现匹配项与对象键不匹配。 You have to escape the strings first. 您必须先转义字符串。 I borrowed this neat escape function to make it work: 我借用了这个简洁的转义功能以使其工作:

 function escapeRegExp(string) { return string.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'); // $& means the whole matched string } var $pencilers = { '\\\\(signed\\\\)': '(assinado)', 'pencils': 'arte', '\\\\[as ': '[como ' }; var $pencils = $("#id_pencils").val(); // eg. Al Williamson [as AW] (signed) // var pen = new RegExp(Object.keys($pencilers).join("|"),"g"); $pencils = $pencils.replace(pen, function(matched){ console.log('before escaping: ', matched); matched = escapeRegExp(matched); console.log('after escaping: ', matched); return $pencilers[matched]; }); console.log($pencils); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id="id_pencils" value="Al Williamson [as AW] (signed)" /> 

You could also turn it around and leave your object keys unescaped, escaping them when building your regex. 您也可以将其转过来,使对象键保持不转义,从而在构建正则表达式时将其转义。 In fact, I'd prefer and recommend to use this approach, as it makes your code more readable. 实际上,我更喜欢并建议使用这种方法,因为它可以使您的代码更具可读性。

 function escapeRegExp(string) { return string.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'); // $& means the whole matched string } var $pencilers = { '(signed)': '(assinado)', 'pencils': 'arte', '[as ': '[como ' }; var $pencils = $("#id_pencils").val(); // eg. Al Williamson [as AW] (signed) // var pen = new RegExp(Object.keys($pencilers).map(escapeRegExp).join("|"),"g"); $pencils = $pencils.replace(pen, function(matched){ return $pencilers[matched]; }); console.log($pencils); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id="id_pencils" value="Al Williamson [as AW] (signed)" /> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM