2014-05-04 6 views
7

Czy istnieje funkcja, która może zastąpić ciąg w ciągu jeden raz w określonym indeksie? Przykład:Korzystanie z .replace() na konkretny indeks

var string1="my text is my text"; 
var string2="my"; 
string1.replaceAt(string2,"your",10); 

a wyjście wypadkowa będzie „mój tekst jest tekst”, lub:

var string1="my text is my text"; 
var string2="my"; 
string1.replaceAt(string2,"your",0); 

w takim przypadku wynik będzie „tekst jest mój tekst”.

+2

'string1 = string1.slice (0,10) + string1.slice (10) .replace (string2," your ");' - wrap in a custom ' replaceAt() 'funkcja jeśli jest wymagana. – nnnnnn

+1

Zobacz też: http://stackoverflow.com/a/1431113/1757964 – APerson

Odpowiedz

1

jeśli nie wiem indeks.

var s = "Stack Overflow"; 
var index = s.indexOf('w'); 
s = s.substr(0, index) + 'x' + s.substr(index + 1); 
+0

Pytanie określa "w określonym indeksie". Ta odpowiedź nie ma znaczenia dla tego pytania. –

+0

Naprawdę nie o to pytano. – divy3993

+0

Nie to, co było potrzebne. – Rice

0
function ReplaceAt(input, search, replace, start, end) { 
    return input.slice(0, start) 
     + input.slice(start, end).replace(search, replace) 
     + input.slice(end); 
} 

jsfiddle here

PS. zmodyfikuj kod, aby dodać puste kontrole, sprawdzanie granic itp.

Powiązane problemy