2015-11-14 35 views
0

我想通過.substring(indexStart, indexEnd)獲取一部分字符串,然後替換原始字符串中的相同部分。獲取子串然後替換

var portion = "my new house".substring(3, 6), 
    portion = "old"; 

// what's next? 
+0

'.replace(「partofstring」,「newvalue」)' –

+0

您提供的代碼根本沒有任何意義。所以這個問題可能不是,下一步是什麼,但是從哪裏開始。 JAvscripts替換方法應該是一個很好的起點:http://www.w3schools.com/jsref/jsref_replace.asp –

+0

我只想替換字符indexStart和indexEnd之間的部分。 –

回答

4

你可以把周圍的子並連接:

var str = "my new house"; 
str = str.slice(0, 3) + "old" + str.slice(6); 
console.log(str); // "my old house" 

當然,這是假設你要替換某些的indeces劃分出部分字符串。如果你只是想更換一個的話,你可以使用:

str = str.replace(/new/g, 'old'); 

(略去g葉形標誌只能更換一次出現。)

+0

非常感謝你:) –

0

你只需要調用「替換」原始字符串找到您收集的子字符串並將其替換爲新的所需字符串。

var oldString = "my new house my new house"; 
var subStr = oldString.substring(indexStart, indexEnd); 
var newValue = "old"; 
var newString = oldString.replace(subStr, newValue); 
+0

這打破了前。 ''newnew house''(這會導致「oldnew house」'而不是''newold house''')。 – Doorknob

+0

另外,如果這部分被重複成「我的新房子我的新房子」這樣的字符串呢?我只想替換indexStart和indexEnd之間的字符 –