var str = \"This is a string\";
var thing = str.replace(\"string\",\"thing\");
console.log( str )
>> \"This is a string\"
console.log( thing )
>> \"Th
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(...)
,