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 方法之外,是否还有其他可以在原地修改字符串而不会给我返回新字符串对象的方法?
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 = string.replace("string", "thing");
。 - Bryce Siedschlaw据我所知,目前没有这样的方法。不过,如果你只是想保持代码简洁,可以将新字符串赋值给旧变量:
var string = "This is a string";
string = string.replace("string", "thing");
当然,这只是让代码看起来更整洁,仍会创建一个新的字符串。
字符串不可变的原因是有其合理性。由于Javascript使用共享调用技术,可变字符串在此情况下将会成为一个问题:
function thinger(str) {
return str.replace("string", "thing");
}
var str = "This is a str";
var thing = thinger(str);
在这种情况下,您希望将字符串按值传递,但实际上并没有。如果 str 是可变的,thinger 将更改 str,这将产生非常奇怪的效果。
// **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(...)
。
string
)。 - Morgan Wilde