JavaScript有没有一种方法可以替换字符串的一部分而不创建新的字符串?

57
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" 

除了 replace 方法之外,是否还有其他可以在原地修改字符串而不会给我返回新字符串对象的方法?


我建议您在任何编程语言中定义变量名称时,不要使用保留字(例如string)。 - Morgan Wilde
2
“string”不是JavaScript中的保留字(来源)。然而,“str”是“未定义”的。你弄混了变量名! - Iso
4个回答

111
不,JavaScript中的字符串是不可变的。

12
如果您不想创建一个新变量,可以尝试这样做:string = string.replace("string", "thing"); - Bryce Siedschlaw

16

据我所知,目前没有这样的方法。不过,如果你只是想保持代码简洁,可以将新字符串赋值给旧变量:

var string = "This is a string";
string = string.replace("string", "thing");

当然,这只是让代码看起来更整洁,仍会创建一个新的字符串。


6

字符串不可变的原因是有其合理性。由于Javascript使用共享调用技术,可变字符串在此情况下将会成为一个问题:

function thinger(str) {
    return str.replace("string", "thing");
}

var str = "This is a str";
var thing = thinger(str);

在这种情况下,您希望将字符串按值传递,但实际上并没有。如果 str 是可变的,thinger 将更改 str,这将产生非常奇怪的效果。


2
Cristian Sanchez所提到的,在JavaScript中字符串是不可变的。 根据任务的需要,我们可以尝试以下方法来解决问题:

 // **fastest** .split(...).join(...)
var string = 'My string'
string = string.split('string').join('thing')
   console.info('with .split-.join', { string }) // 'My thing'

// **good old wine** .replace('...','...') as mentioned above
string = 'My string'
string = string.replace('string','thing')
   console.info('with .replace', { string }) // 'My thing'

// **ES6 string interpolation**
string = (arg) => `My ${arg}`
   console.info('with interpolation 1', { string: string('string') }) // 'My string'
   console.info('with interpolation 2', { string: string('thing') }) // 'My thing'

注意:这些方法有一些花哨的方式,如使用 ..indexOf(...) 和 .substring(...).charAt(...)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接