How can I replace a string by range?

浪子不回头ぞ 提交于 2020-07-05 06:17:10

问题


I need to replace a string by range Example:

string = "this is a string";//I need to replace index 0 to 3 whith another string Ex.:"that"
result = "that is a string";

but this need to be dinamically. Cant be replace a fixed word ...need be by range

I have tried

           result = string.replaceAt(0, 'that');

but this replace only the first character and I want the first to third


回答1:


function replaceRange(s, start, end, substitute) {
    return s.substring(0, start) + substitute + s.substring(end);
}

var str = "this is a string";
var newString = replaceRange(str, 0, 4, "that"); // "that is a string"



回答2:


var str = "this is a string";
var newString = str.substr(3,str.length);
var result = 'that'+newString

substr returns a part of a string, with my exemple, it starts at character 3 up to str.length to have the last character...

To replace the middle of a string, the same logic can be used...

var str = "this is a string";
var firstPart = str.substr(0,7); // "this is "
var lastPart = str.substr(8,str.length); // " string"
var result = firstPart+'another'+lastPart; // "this is another string"



回答3:


I simple substring call will do here

var str = "this is a string";
var result = "that" + str.substring(4);

Check out a working jsfiddle.



来源:https://stackoverflow.com/questions/12568097/how-can-i-replace-a-string-by-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!