67
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?

2
  • I suggest you never use reserved words (such as string) when defining variable names in any language. Commented Mar 19, 2014 at 19:14
  • 2
    string is not a reserved word in JavaScript (source). However, str is undefined. You messed up the variable names! Commented Mar 19, 2014 at 19:18

4 Answers 4

123

No, strings in JavaScript are immutable.

Sign up to request clarification or add additional context in comments.

1 Comment

You could do something like this though if you don't want to create a new variable: string = string.replace("string", "thing");
19

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.

Comments

6

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.

Comments

2

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(...),

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.