我知道這是愚蠢的,但我覺得這個創意早:
'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