Javascript 为什么(!condition){console.log(condition)}语句显示true
我想创建一个String方法,它接受一个RegExp和一个回调,然后按RegExp拆分字符串,并在拆分数组中插入回调的返回值。简言之,它将执行以下操作:Javascript 为什么(!condition){console.log(condition)}语句显示true,javascript,regex,Javascript,Regex,我想创建一个String方法,它接受一个RegExp和一个回调,然后按RegExp拆分字符串,并在拆分数组中插入回调的返回值。简言之,它将执行以下操作: "a 1 b 2 c".method(/\d/, function ($1) { return $1 + 1; }) => [a, 2, b, 3, c] "a b c d e".method(/\d/, function ($1) { return $1 + 1; }) => ["a b c d e"] 如果字
"a 1 b 2 c".method(/\d/, function ($1) { return $1 + 1; })
=> [a, 2, b, 3, c]
"a b c d e".method(/\d/, function ($1) { return $1 + 1; })
=> ["a b c d e"]
如果字符串与RegExp不匹配,它应该返回一个数组,如下所示:
"a 1 b 2 c".method(/\d/, function ($1) { return $1 + 1; })
=> [a, 2, b, 3, c]
"a b c d e".method(/\d/, function ($1) { return $1 + 1; })
=> ["a b c d e"]
我写了这段代码,但它不像我想的那样工作:
String.prototype.preserveSplitReg = function(reg, func) {
var rtn = [],
that = this.toString();
if (!reg.test(that)) {
console.log(reg, that, reg.test(that));
return [that];
}
...
}
仅当字符串与reg
不匹配时才应调用console.log,对吗?但有时它会记录(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
“请参见http://www.w3.org/TR/html5-diff/ 用于更改的元素和属性,以及过时的元素和“
/*?/g
控制台日志为true。我不明白为什么。非常感谢您的帮助。这是
基本上,带有g
修饰符的正则表达式不能正确重置,因此多个test()
调用在true和false
之间切换
- 另请参见此答案:了解更多详细信息