Un altro approccio quando è necessario sostituire completamente una stringa in un indice specifico, con esattamente la stessa chiamata di funzione con String.prototype.replace
potrebbe essere questo:
String.prototype.replaceAt = function(index, fromString, toString) {
let hasWrongParams = typeof index !== 'number'
|| !fromString || typeof fromString !== 'string'
|| !toString || typeof toString !== 'string';
if(hasWrongParams) return '';
let fromIndex = index;
let toIndex = index + fromString.length;
return this.substr(0, fromIndex) + toString + this.substr(toIndex);
}
https://gist.github.com/kwnccc/9df8554474e39f4b17a07efbbdf7971c
Ad esempio:
let string = 'This is amazing world, it's still amazing!';
string.replaceAt(8, 'amazing', 'worderful');
// 'This is worderful world, it's still amazing!'
string.replaceAt(34, 'amazing', 'worderful');
// 'This is amazing world, it's still worderful!'
fonte
2017-02-23 16:35:36
Qual è il motivo per il collegamento di questa funzione di utilità al prototipo .. – Exception
+1, mi ha richiesto più tempo per capire più o meno la stessa cosa! – adeneo
@Exception OTOH, la possibilità di collisione nello spazio dei nomi è trascurabile con questo nome di metodo ;-) –