我知道这很愚蠢,但是今天早上我觉得很有创造力:
'one two, one three, one four, one'
.split(' ') // array: ["one", "two,", "one", "three,", "one", "four,", "one"]
.reverse() // array: ["one", "four,", "one", "three,", "one", "two,", "one"]
.join(' ') // string: "one four, one three, one two, one"
.replace(/one/, 'finish') // string: "finish four, one three, one two, one"
.split(' ') // array: ["finish", "four,", "one", "three,", "one", "two,", "one"]
.reverse() // array: ["one", "two,", "one", "three,", "one", "four,", "finish"]
.join(' '); // final string: "one two, one three, one four, finish"
所以,实际上,您需要做的就是将此函数添加到String原型中:
String.prototype.replaceLast = function (what, replacement) {
return this.split(' ').reverse().join(' ').replace(new RegExp(what), replacement).split(' ').reverse().join(' ');
};
然后像这样运行它:
str = str.replaceLast('one', 'finish');
您应该知道的一个限制是,由于该函数是按空格分割的,因此您可能找不到/替换任何空格。
实际上,现在我想到了,您可以通过使用空令牌拆分来解决“空间”问题。
String.prototype.reverse = function () {
return this.split('').reverse().join('');
};
String.prototype.replaceLast = function (what, replacement) {
return this.reverse().replace(new RegExp(what.reverse()), replacement.reverse()).reverse();
};
str = str.replaceLast('one', 'finish');