Home > Net >  Can I replace items in string based off of an array using vanilla javascript?
Can I replace items in string based off of an array using vanilla javascript?

Time:10-01

I'm using a helper function to replace all the instances of a word in a string with a "-". I would like to search an array and replace any instance from the array. Below is the current snippet that can only replace on string at a time.

let x = document.querySelector("form.form").elements;
    let input = x["formName"].value;

        function replaceAll(string, search, replace) {
          return string.split(search).join(replace);
          }


    let noStop = replaceAll(input, "example", "-");

CodePudding user response:

You can do it with regex. You need to use OR | and the global flag, g, which matches all the possible matches, essentially turning replace(regex) to replaceAll.

let words = ['hi','hello','dear']
let regex = new RegExp(words.join('|'), 'g') //  /hi|hello|dear/g

let string = 'hi dear, are you there?, hello?'
let result = string.replace(regex, '-')

console.log(result)

CodePudding user response:

Use map() to call a function on every element of an array.

newArray = oldArray.map(s => s.replaceAll(search, replace));

Notice that there's a built-in replaceAll() method, you don't need to write your own function.

  • Related