简体   繁体   中英

Can someone explain this particular use of the replace() method in Javascript?

I am learning Javascript and came across a practice problem on the web that I was able to solve but didn't match the given solution which was much more compact. The follow code just takes a word, reverses the letters and then replaces a, e, o, u with numbers. I did a lot of research but can't seem to understand how the following arrow function parameter of the replace() method works:

    match => replaceChars[match]

Here is the complete code:

    var x = "orange";
    var y = x.split("").reverse().join("");
    var replaceChars={ "a": 0 , "e": 6, "o": 2, "u": 9 };
    var t = y.replace(/[aeou]/g,match => replaceChars[match]);
    console.log(t)

Edit: Thanks for the quick answers. I get it now. I just needed to write it out like this to fully understand:

    var x = "orange";
    var y = x.split("").reverse().join("");
    var replaceChars={ "a": 0 , "e": 6, "o": 2, "u": 9 };
    function matchFunc(match){
    x = replaceChars[match];
    return x;}
    console.log (replaceChars["a"])
    var t = y.replace(/[aeou]/g,matchFunc);
    console.log(t)

This part is called an arrow function and it is defined like so:

arguments => 
{ 
  block of code
}

Arrow functions were added in ES6 and you can use them as callback functions (instead of using a standard anonymous function). In this particular example, when a character is part of the regular expression, then the arrow function executes that replaces is by the equivalent number in the object replaceChars.

String.prototype.replace accepts a second parameter that can either be a string that each matched occurrence is replaced with, or a function that is called with the match for each match, whose return value is used to replace that match.

In your example, the replaceChars object provides the replacement for each character that could be matched.

This may make it more clear:

 var y = "abceOou".split("").reverse().join(""); var replaceChars={ "a": 0, "e": 6, "o": 2, "u": 9 }; var t = y.replace(/[aeou]/g,match=>{ console.log(`Replacing ${match} with ${replaceChars[match]}`); return replaceChars[match]; }); console.log(t)

The /g is a regular expression that selects every instance of each character within "aeou" (instead of only selecting the first occurrence of "aeou") and replaces them with the value of matchFunc => replaceChars[matchFunc] .


For example, without /g :

var string = "123 example 123 string 123";
string.replace("123", "Test"); // Replaces first instance of string "123"

Would print: "Test example 123 string 123"


And with /g :

var string = "123 example 123 string 123";
string.replace(/[123]/g, "Test"); // Replaces every separate character with 1, 2 or 3.

Would print: "TestTestTest example TestTestTest string TestTestTest"

This is because it selects every instance of "1", "2" and "3", and replaces it with "Test".

First off, your question is a little confusing, so next time try proof-reading your question before posting.

Let's say you have the function

const replaceChars={ "a": 0 , "e": 6, "o": 2, "u": 9 };
const replace = letter => replaceChars[letter]

(I changed the variable name for clarity). This is the same as

var replaceChars={ "a": 0 , "e": 6, "o": 2, "u": 9 };
function replace(letter) { 
  return replaceChars[letter] 
}

but much more succinct.

Try calling either function in your console:

replace('a') // returns 0
replace('e') // returns 6

That function is called for each of the matched letters in y.replace(...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM