我知道这是愚蠢的,但我觉得这个创意早:
'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.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');
好主意。首先需要转义该字符串(尽管不是与她的示例数据一致),这是非平凡的。 :-( – 2010-04-28 13:13:02
非常感谢你 – Ruth 2010-04-28 13:26:01
@Ruth no prob!@TJ是的,事实的确如此:Ruth如果最终得到的是包含用于正则表达式的特殊字符的“词”,则需要TJ说这是一个有点棘手的问题(虽然不是不可能) – Pointy 2010-04-28 21:56:41