javascript 是否有一种方法可以在不创建新字符串的情况下替换部分字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6192169/
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
Does javascript have a method to replace part of a string without creating a new string?
提问by djacobs7
var str = "This is a string";
var thing = str.replace("string","thing");
console.log( str )
>> "This is a string"
console.log( thing )
>> "This is a thing"
Is there another method I can use, besides replace, that will alter the string in place without giving me a new string object?
除了替换之外,我是否可以使用另一种方法来改变字符串而不给我一个新的字符串对象?
回答by Cristian Sanchez
No, strings in JavaScript are immutable.
不,JavaScript 中的字符串是不可变的。
回答by Jan-Peter Vos
Not that i am aware of, however if the reason you want to do this is just to keep your code clean you can just assign the new string the the old variable:
我不知道,但是如果你想这样做的原因只是为了保持你的代码干净,你可以将新字符串分配给旧变量:
var string = "This is a string";
string = string.replace("string", "thing");
Of course this will just make the code look a bit cleaner and still create a new string.
当然,这只会使代码看起来更简洁,并且仍会创建一个新字符串。
回答by Poyoman
There is a reason why strings are immutable. As Javascript use call-by-sharing technic, mutable string would be a problem in this case :
字符串不可变是有原因的。由于 Javascript 使用共享调用技术,在这种情况下可变字符串将是一个问题:
function thinger(str) {
return str.replace("string", "thing");
}
var str = "This is a str";
var thing = thinger(str);
In this situation you want your string to be passed by value, but it is not. If str was mutable, thinger would change str, that would be a really strange effect.
在这种情况下,您希望您的字符串按值传递,但事实并非如此。如果 str 是可变的,thinger 会改变 str,那将是一个非常奇怪的效果。