How to replace contents of an array with elements of another array JQUERY

4

I have a question about whether it is possible, and if it is possible, how can you replace content in an array, by the content of another array.

For example:
Input: "blue red and green"

find = ["azul", "rojo", "verde", "y"] replace = ["blue", "red", "green", "and"] texto = texto.replace(find, replace) return text

Exit: "blue red and green"

Thank you very much, and sorry if I asked the question badly, I'm new in stackoverflow, but sometimes I have been insulted for not using the elements to separate query code.

    
asked by Esteban Fernández 19.03.2018 в 19:38
source

1 answer

4

You could use:

  • Array.forEach , so that for each fix% find word, search for and replace by the word in the same position within the repalce fix.

  • [OPTIONAL] If the intention is to find and replace the exact word, then you should use the regular expression:

    /\b(palabra)\b/
    

    This would avoid mistakes when replacing words contained within a word.

Demo without RegExp

function doIt() {
  let text = "azul rojo yellow y verde"
  let find = ["azul", "rojo", "verde", "y", "yellow"]
  let replace = ["blue", "red", "green", "and", "amarillo"]

  find.forEach((value, index) => {
    text = text.replace(new RegExp(value, 'g'), replace[index])
  })
  return text
}

console.log(doIt());

Demo with RegExp

function doIt() {
  let text = "azul rojo yellow y verde"
  let find = ["azul", "rojo", "verde", "y", "yellow"]
  let replace = ["blue", "red", "green", "and", "amarillo"]

  find.forEach((value, index) => {
    text = text.replace(new RegExp('\b(' + value + ')\b', 'g'), replace[index])
  })
  return text
}

console.log(doIt());
    
answered by 19.03.2018 / 20:01
source