Does javascript have a method to replace part of a string without creating a new string?

前端 未结 4 1704
北海茫月
北海茫月 2020-12-16 09:27
var str = \"This is a string\";
var thing = str.replace(\"string\",\"thing\");

console.log( str )
>> \"This is a string\" 

console.log( thing )
>> \"Th         


        
4条回答
  •  隐瞒了意图╮
    2020-12-16 10:10

    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.

提交回复
热议问题