2012-12-18 17 views
5

Come è possibile sostituire una sottostringa di una stringa in base alla posizione iniziale e alla lunghezza?Sostituisce la sottostringa in una stringa con intervallo in JavaScript

speravo in qualcosa di simile:

var string = "This is a test string"; 
string.replace(10, 4, "replacement"); 

in modo che string sarebbe uguale

"this is a replacement string" 

..ma non riesco a trovare niente di simile.

Qualsiasi aiuto apprezzato.

risposta

7

Ti piace questa:

var outstr = instr.substr(0,start)+"replacement"+instr.substr(start+length); 

è possibile aggiungerlo al prototipo della stringa:

String.prototype.splice = function(start,length,replacement) { 
    return this.substr(0,start)+replacement+this.substr(start+length); 
} 

(Io chiamo questo splice perché è molto simile alla funzione Array con lo stesso nome)

+0

vedo che il tuo approccio è anche stupidamente dv'ed ': /' – VisioN

2

Short RegExp versione:

str.replace(new RegExp("^(.{" + start + "}).{" + length + "}"), "$1" + word); 

Esempio:

String.prototype.sreplace = function(start, length, word) { 
    return this.replace(
     new RegExp("^(.{" + start + "}).{" + length + "}"), 
     "$1" + word); 
}; 

"This is a test string".sreplace(10, 4, "replacement"); 
// "This is a replacement string" 

DEMO:http://jsfiddle.net/9zP7D/

+2

Ecco come lo farei personalmente. ♥ regex. – elclanrs

+1

I regexes sono tuttavia inutilmente lenti: http://jsperf.com/string-splice –

0

Il Underscore String library ha un metodo splice che funziona esattamente come specificato.

_("This is a test string").splice(10, 4, 'replacement'); 
=> "This is a replacement string" 

Ci sono molte altre funzioni utili nella libreria pure. Funziona a 8kb ed è disponibile su cdnjs.

+0

@ cr0nicz Mi riferivo a Underscore.string. Controlla il link. – tghw

0

Per quello che vale, questa funzione verrà sostituita in base a due indici anziché al primo indice e alla lunghezza.

splice: function(specimen, start, end, replacement) { 
    // string to modify, start index, end index, and what to replace that selection with 

    var head = specimen.substring(0,start); 
    var body = specimen.substring(start, end + 1); // +1 to include last character 
    var tail = specimen.substring(end + 1, specimen.length); 

    var result = head + replacement + tail; 

    return result; 
} 
Problemi correlati