3

This is a simple replace() question - and I can't get it working to replace a substring in the function below.

function linkOnClick(){
    var anyNameYouLike = 'some sort of text/string right here';
    anyNameYouLike.replace('right','in');
    alert(anyNameYouLike)
}

It should return "some sort of text/string in here" but doesn't. What am I doing wrong? I'm fairly new with Javascript (if it isn't obvious...)

Mukul Goel
  • 8,387
  • 6
  • 37
  • 77
mseifert
  • 5,390
  • 9
  • 38
  • 100
  • 4
    Please make sure you're using the correct tags. The code isn't in Java. – NPE Nov 25 '12 at 08:20
  • 2
    it IS returning a String but you are not saving it... look at ivanovic's answer – thepoosh Nov 25 '12 at 08:21
  • I recommend looking this kind of thing up on [mdn](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace). Just google `javascript mdn `. – beatgammit Nov 25 '12 at 08:24

2 Answers2

21
anyNameYouLike = anyNameYouLike.replace('right','in');
Juvanis
  • 25,802
  • 5
  • 69
  • 87
  • 2
    Funny how long something as simple as this can take to figure out. Thank you for taking the time to help. – mseifert Nov 25 '12 at 08:25
  • Javascript `replace` handles only first occurrence without global flag. See http://stackoverflow.com/questions/1144783/replacing-all-occurrences-of-a-string-in-javascript. – Vadzim Jan 14 '14 at 14:35
9

In javascript, strings are immutable (they are never modified). As such, the .replace() function does not modify the string you call it on. Instead, it returns a new string. So, if you want anyNameYouLike to contain the modified string, you have to assign the result to it like this:

anyNameYouLike = anyNameYouLike.replace('right','in');

For more info, refer to the MDN description of the .replace() method which says this:

Returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.

And, in the description of the .replace() method, it says this:

This method does not change the String object it is called on. It simply returns a new string.

jfriend00
  • 683,504
  • 96
  • 985
  • 979