我的字符串中有一部分from, to我想替换为另一个字符串replace_string。我的代码应该可以工作,但是如果有另一个部分,比如返回的子字符串呢?
var from=10, to=17;
//...
str = str.replace(str.substring(from, to), replace_string);
例如:
from=4,to=6
str = "abceabxy"
replace_string = "zz"
str 应该是“abcezzxy”
我的字符串中有一部分from, to我想替换为另一个字符串replace_string。我的代码应该可以工作,但是如果有另一个部分,比如返回的子字符串呢?
var from=10, to=17;
//...
str = str.replace(str.substring(from, to), replace_string);
例如:
from=4,to=6
str = "abceabxy"
replace_string = "zz"
str 应该是“abcezzxy”
你想做的很简单!剪下并替换字符串。这是您需要的基本工具,scissor并且glue!哎呀,我的意思是string.Split()和string.Replace()。
如何使用?
好吧,我不确定您是否要使用string.Split(),但您已经使用过string.Replace(),所以就这样吧。
String.Replace 使用两个参数,就像这样("one", "two"),您需要确保您没有将 a 替换为charastring或 a替换为stringa char。它们被用作:
var str="Visit Microsoft!";
var n=str.replace("Microsoft","W3Schools");
你的代码:
var from=10, to=17;
//...
var stringGot = str.replace(str.substring(from, to), replace_string);
你应该做的是先拆分代码,然后替换第二个a字母!正如您在示例中想要的那样。那是一种方式!
首先,拆分字符串!然后将第二个a字母替换为z.
对于 String.Replace,请参阅:http ://www.w3schools.com/jsref/jsref_replace.asp
对于 String.SubString:http ://www.w3schools.com/jsref/jsref_substring.asp
对于 String.Split:http ://www.w3schools.com/jsref/jsref_split.asp
字符串是不可变的。这意味着它们在第一次实例化后不会改变。每个操作字符串的方法实际上都会返回一个新的字符串实例。因此,您必须将结果分配回变量,如下所示:
str = str.replace(str.substring(from, to), replace_string);
更新:但是,首先执行此操作的更有效方法如下。它也不太容易出错:
str = str.substring(0, from) + replace_string + str.substring(to);
看到这个小提琴:http: //jsfiddle.net/cFtKL/
它通过循环运行这两个命令 100,000 次。第一个需要大约 75 毫秒,而后者需要 20 毫秒。