[英]Cut out, and replace a part of a string
有一个在我的字符串的一部分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")
你需要确保的是,你是不是更换一个char
用string
或string
用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
字母! 如您所愿。 那是一种方式!
首先,分割字符串! 然后用z
替换第二a
字母。
对于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毫秒。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.