字符串在 JavaScript 中是不可变的,所以这样的事情不会起作用
// can't reassign `this` in String.prototype method !
this = this.replace(f,r)
相反,您必须从函数中返回一个新字符串
String.prototype.replaceAll = function replaceAll(f,r) {
if (this.indexOf(f) === -1)
return this.toString()
else
return this.replace(f, r).replaceAll(f,r)
}
console.log('foobar foobar'.replaceAll('foo', 'hello')) // => 'hellobar hellobar'
console.log('foobar foobar'.replaceAll('o', 'x')) // => 'fxxbar fxxbar'
如果您不介意依赖像 String.prototype.indexOf 和 String.prototype.replace 这样的内置插件,那么这就是简短的答案
如果您也想从头开始实现这些,您可以使用非常基本的 JavaScript 来实现。您不必使用 while 循环`。你可以,但是像……这样的陈述
所以我真的需要在while循环中使用第一个函数。
……是假的。
让我们从一个基本的find 函数开始。这就像String.prototype.indexOf
function find(s, x) {
function loop(s, pos) {
if (s.substring(0, x.length) === x)
return pos
else if (s === '')
return -1
else
return loop(s.substring(1), pos + 1)
}
return loop(s, 0)
}
console.log(find('foobar', 'f')) // => 0
console.log(find('foobar', 'bar')) // => 3
console.log(find('foobar', 'x')) // => -1
console.log(find('foobar', '')) // => 0
然后是一个replace 函数,该函数用于将x 的单个实例替换为字符串y 中的s
function replace(s, x, y, idx) {
// idx is an optional parameter here for optimizing replaceAll
// you'll see it used in the next example
if (idx === undefined)
return replace(s, x, y, find(s, x))
else if (idx === -1)
return s
else
return s.substring(0, idx) + y + s.substring(idx + x.length)
}
console.log(replace('foobar', 'foo', 'hello')) // => 'hellobar'
console.log(replace('foobar', 'bar', 'hello')) // => 'foohello'
那么,实现replaceAll就是一个简单的递归函数
function replaceAll(s, x, y) {
var idx = find(s, x)
if (idx === -1)
return s
else
// use 4th parameter in replace function so index isn't recalculated
return replaceAll(replace(s, x, y, idx), x, y)
}
console.log(replaceAll('foobar foobar', 'foo', 'hello')) // => 'hellobar hellobar'
console.log(replaceAll('foobar foobar', 'o', 'x') ) // => 'fxxbar fxxbar'
如果你愿意,你可以在String.prototype 上实现所有这些功能,所以像'foobar'.replaceAll('o', 'x') 这样的东西可以工作。
如果你不喜欢find,可以使用原生的String.prototype.indexOf。另一方面,如果您将此作为练习,并且尝试从头开始实施,您甚至可以不依赖我在这里使用的String.prototype.substring。
另外,你的代码在这里运行良好
String.prototype.replaceAll = function(f,r) {
return this.split(f).join(r);
};
'foobar foobar'.replaceAll('foo', 'hello')
// => "hellobar hellobar"
'foobar foobar'.split('foo').join('hello')
// => "hellobar hellobar"