javascript 如何按范围替换字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12568097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:32:14  来源:igfitidea点击:

How can I replace a string by range?

javascriptstringreplace

提问by DevMobile

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

但这仅替换第一个字符,我想要第一个到第三个

回答by Alexander Pavlov

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"

回答by Salketer

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...

substr 返回字符串的一部分,以我的示例为例,它从字符 3 开始,直到 str.length 以具有最后一个字符...

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"

回答by Ash Burlaczenko

I simple substringcall will do here

我简单的子串调用将在这里完成

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

Check out a working jsfiddle.

查看一个有效的jsfiddle