skip to Main Content

Here I have more than 30 words that wish to replace, how can I improve the efficiency and no need to write more than 30 replace?

"sample string".split(" ").map((x) => {
      return x
        .replace(/bmanb/g, "manchester")
        .replace("/butdb/g", "united")...(still have 30 words to go)
    })

3

Answers


  1. You could do that dynamically with a lookup matrix that stores all your replacements.

    const replacements = [
      [/bmanb/, "manchester"],
      [/butdb/, "united"]
    ];
    
    const inputString = "sample string man man utd";
    
    const result = inputString
      .split(" ")
      .map(word => replacements.find(r => r[0].test(word))?.[1] || word)
      .join(" ");
    
    console.log(result);
    Login or Signup to reply.
  2. If you are only replacing words, i.e. using the b boundary before and after the regex and no non-alphanumeric character to match, then use a look-up object, whose keys are the words you want to replace. One generic regex could even suffice:

    const translations = {
        "man": "manchester",
        "utd": "united",
    };
    
    const str = "this evening man utd will play again"; 
    const result = str.replace(/w+/g, word => translations[word] ?? word);
    
    console.log(result);
    Login or Signup to reply.
  3. // Define a string with multiple patterns to replace
    let inputString = "Hello, $name! Today is $day.";
    
    // Define a mapping of patterns and their replacement values
    let replacements = {
      $name: "John",
      $day: "Monday"
    };
    
    // Create a regular expression pattern that matches all keys in the replacements object
    let pattern = new RegExp(Object.keys(replacements).join("|"), "g");
    
    // Use the regular expression with .replace() to replace all matching patterns
    let resultString = inputString.replace(pattern, (match) => replacements[match]);
    
    console.log(resultString); // output "Hello, John! Today is Monday."
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search