我想创建一个String方法,它接受一个RegExp和一个回调,然后通过RegExp拆分String,并在split数组中插入回调的返回.简而言之,它会做这样的事情:
"a 1 b 2 c".method(/\d/, function ($1) { return $1 + 1; })
=> [a, 2, b, 3, c]
Run Code Online (Sandbox Code Playgroud)
如果String与RegExp不匹配,它应该返回一个数组,如下所示:
"a b c d e".method(/\d/, function ($1) { return $1 + 1; })
=> ["a b c d e"]
Run Code Online (Sandbox Code Playgroud)
我写了这段代码,但它没有像我想的那样工作:
String.prototype.preserveSplitReg = function(reg, func) {
var rtn = [],
that = this.toString();
if (!reg.test(that)) {
console.log(reg, that, reg.test(that));
return [that];
}
...
}
Run Code Online (Sandbox Code Playgroud)
只有当String不匹配时才应该调用console.log reg,对吧?但有时它会记录(reg, that, true).麻烦的字符串reg是:
"See <url>http://www.w3.org/TR/html5-diff/</url> for changed elements and attributes, …Run Code Online (Sandbox Code Playgroud)