我想通过.substring(indexStart, indexEnd)
获取字符串的一部分,然后替换原始字符串中的相同部分。
var portion = "my new house".substring(3, 6),
portion = "old";
// what's next?
最佳答案
您可以采用周围的子字符串并进行连接:
var str = "my new house";
str = str.slice(0, 3) + "old" + str.slice(6);
console.log(str); // "my old house"
当然,这是假设您要替换某些索引标记为字符串的部分。如果您只想替换一个单词,则可以使用:
str = str.replace(/new/g, 'old');
(省略
g
lobal标志以仅替换第一次出现的标志。)关于javascript - 获取子字符串,然后替换,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33714588/