2012-12-18 24 views
5

Jak mogę zamienić podciąg łańcucha na podstawie pozycji początkowej i długości?Zastąp ciąg znaków ciągiem o zakresie w kodzie JavaScript

Miałem nadzieję na coś takiego:

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

tak że string wyniesie

"this is a replacement string" 

..ale nie mogę znaleźć czegoś takiego.

Każda pomoc doceniona.

Odpowiedz

7

Jak to:

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

Można go dodać do prototypu napisu za:

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

(ja nazywam to splice ponieważ jest bardzo podobna do funkcji Array o tej samej nazwie)

+0

widzę, że Twoje podejście jest również głupio dv'ed ': /' – VisioN

2

Wersja z krótką regułą:

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

Przykład:

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

To w jaki sposób to zrobić osobiście. ♥ regex. – elclanrs

+1

Regeksy są niepotrzebnie powolne: http://jsperf.com/string-splice –

0

Underscore String library ma metodę składania mRNA, który działa dokładnie tak, jak podano.

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

Istnieje wiele innych przydatnych funkcji w bibliotece. Zegara w 8kb i jest dostępny na cdnjs.

+0

@ cr0nicz Miałem na myśli Underscore.string. Sprawdź link. – tghw

0

Co jest warte, funkcja ta zostanie zastąpiona na podstawie dwóch indeksów zamiast pierwszego indeksu i długości.

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; 
} 
Powiązane problemy