【发布时间】:2015-06-23 07:48:46
【问题描述】:
我正在为输入文本字段编写一些正则表达式,但在转义“+”或“?”等特殊字符时遇到了一些麻烦。
我已经使用了thesetwo 问题,它们适用于 c+ 之类的字符串,但如果我输入 c++,我会收到以下错误控制台Invalid regular expression: /c++/: Nothing to repeat
代码如下:
$('input').keyup(function(){
var val = $(this).val().trim().toLowerCase();
// from: https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
//val.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
//from: https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
val = val.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
var re = new RegExp(val, 'ig');
console.log(re);
});
这是jsFiddle example of the issue
谢谢
【问题讨论】:
标签: javascript regex escaping