This question already has an answer here:
这个问题已经有了答案:
- What is wrong with my date regex? [duplicate] 2 answers
- 我的约会regex怎么了?(重复)2的答案
I want to make a String method, which accepts a RegExp and a callback, then splits String by RegExp, and inserts callback's return in split array. In short, it would do something like this:
我想创建一个String方法,它接受RegExp和回调,然后通过RegExp分割字符串,并在分割数组中插入回调的返回。简而言之,它将做如下事情:
"a 1 b 2 c".method(/\d/, function ($1) { return $1 + 1; })
=> [a, 2, b, 3, c]
In case the String doesn't match the RegExp, it should return an array, like this:
如果字符串与RegExp不匹配,它应该返回一个数组,如下所示:
"a b c d e".method(/\d/, function ($1) { return $1 + 1; })
=> ["a b c d e"]
I wrote this code, but it doesn't work as I thought:
我写了这段代码,但它不像我想的那样:
String.prototype.preserveSplitReg = function(reg, func) {
var rtn = [],
that = this.toString();
if (!reg.test(that)) {
console.log(reg, that, reg.test(that));
return [that];
}
...
}
The console.log should be called ONLY when the String doesn't match reg
, right? But sometimes it logs (reg, that, true)
. That troublesome String and reg
were:
控制台。只有当字符串不匹配reg时才调用日志,对吗?但有时它会记录(reg, that, true)那个麻烦的字符串和reg是:
"See <url>http://www.w3.org/TR/html5-diff/</url> for changed elements and attributes, as well as obsolete elements and"
/<url>.*?<\/url>/g
console logs true. I can't figure out why. Any help would be highly appreciated.
真正的控制台日志。我搞不懂为什么。如有任何帮助,我们将不胜感激。
1 个解决方案
#1
6
This is due to a bug in Javascript RegEx engine (ECMAScript3)
这是由于Javascript RegEx引擎(ECMAScript3)中的一个错误造成的。
Basically a regex with the g
modifier doesn't reset correctly, so multiple test()
calls toggle between true and false
.
基本上,带有g修饰符的正则表达式不能正确重置,因此多个测试()调用在true和false之间进行切换。
- See also this answer: https://*.com/a/3827500/548225 for more details.
- 详情请参见:https://*.com/a/3827500/548225。
#1
6
This is due to a bug in Javascript RegEx engine (ECMAScript3)
这是由于Javascript RegEx引擎(ECMAScript3)中的一个错误造成的。
Basically a regex with the g
modifier doesn't reset correctly, so multiple test()
calls toggle between true and false
.
基本上,带有g修饰符的正则表达式不能正确重置,因此多个测试()调用在true和false之间进行切换。
- See also this answer: https://*.com/a/3827500/548225 for more details.
- 详情请参见:https://*.com/a/3827500/548225。