Javascript replace() function [duplicate]

2019-02-18 14:35发布

问题:

This question already has an answer here:

  • Replace function not replacing [duplicate] 2 answers

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

回答1:

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


回答2:

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.