So che questo è stupido, ma mi sento creativa di questa mattina:
'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"
Quindi, in realtà, tutto quello che avresti bisogno di fare è aggiungere questa funzione al prototipo String:
String.prototype.replaceLast = function (what, replacement) {
return this.split(' ').reverse().join(' ').replace(new RegExp(what), replacement).split(' ').reverse().join(' ');
};
quindi eseguirlo in questo modo: str = str.replaceLast('one', 'finish');
una limitazione che si deve sapere è che, dal momento che la funzione è la divisione dallo spazio, è
probabilmente non riesce a trovare/sostituire nulla con uno spazio.
In realtà, ora che ci penso, si potrebbe aggirare il problema dello "spazio" dividendo con un gettone vuoto.
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');
Buona idea. Bisogna prima scappare da quella stringa (anche se non con i suoi dati di esempio, concessi), che non è banale. :-( –
Grazie mille – Ruth
@Ruth no prob! @TJ sì, in effetti è vero: Ruth se finisci con "parole" che stai cercando che includono i caratteri speciali usati per le espressioni regolari, avresti bisogno per "sfuggire" a quelli che, come dice TJ, è un po 'complicato (non impossibile però) – Pointy