skip to Main Content

The .replace(/w+/g), function) works well when replacing one single word inside standardizeMap, however, it fails when it comes to multiple words.

Sample input (Case 1):

const standardizeMap = new Map([
    ["Hello world", "How are you"],
    ["apple pen", "appleP"],
    ["Swaziland", "Eswatini"])
"Hello world I have an apple pen in Swaziland".replace(/w+/g, (word) =>
        standardizeMap.get(word) ? standardizeMap.get(word) : word
      )

Output:

Hello world I have an apple pen in Eswatini

Expected output:

How are you I have an appleP in Eswatini

Sample input (Case 2):

"Hello world I have an apple penin Swaziland".replace(/w+/g, (word) =>
        standardizeMap.get(word) ? standardizeMap.get(word) : word
      )

Expected output:

How are you I have an apple penin Eswatini

How can I achieve it?

2

Answers


  1. You need to iterate over each key value in standardizeMap and replace all occurrences of the key.

    const standardizeMap = new Map([
      ["Hello world", "How are you"],
      ["apple pen", "appleP"],
      ["Swaziland", "Eswatini"],
    ]);
    
    const input = "Hello world I have an apple pen in Swaziland";
    
    function replaceString(map, input) {
      let output = input;
      for (const [key, value] of map) {
        output = output.replace(key, value);
      }
      return output;
    }
    
    console.log(replaceString(standardizeMap, input));
    
    Login or Signup to reply.
  2. Calling String.replace(/w+/g, (word) => doStuff()) (or replaceAll, same thing except that replaceAll requires the ‘g’ flag) will let the method perform the replacement for each matching sequences of w+. You can see them using the console logging:

    >> let text = "Hello world I have an apple pen in Swaziland";
    >> text.replace(/w+/g, function(word) {console.log(word);return word});
    Hello
    world
    I
    have
    an
    apple
    pen
    in
    Swaziland
    

    So, you should loop over your map and for each entry, replace in the text all occurrences of its key to its value.

    Instead, you should loop through your map and, for each entry, replace in the text all occurrences of the entry’s key with its value, as shown below for example.

    let text = "Hello world I have an apple pen in Swaziland" ;
    for (const [key, value] of s) text = text.replaceAll(key, s.get(key));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search