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

前端 未结 4 1702
北海茫月
北海茫月 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 09:48

    No, strings in JavaScript are immutable.

    0 讨论(0)
  • 2020-12-16 09:56

    There is a reason why strings are immutable. As Javascript use call-by-sharing technic, mutable string would be a problem in this case :

    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.

    0 讨论(0)
  • 2020-12-16 09:58

    As Cristian Sanchez mentioned, in javascript strings are immutable. Depending on the task we can try to work around with the following approaches:

     // **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'

    Note: there are fancy ways with such approaches as ..indexOf(...) and .substring(...), .charAt(...),

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题