Home > Back-end >  Javascript replace string with list from array
Javascript replace string with list from array

Time:05-10

I have a string that is a normal sentence. I need to replace the characters in the string if they are found in a given array. For example,

const arr = ["(model: Audi)", "(model: Kia)"];

if the string is:

"How is your (model: Audi) today?";

The result should be "How is your Audi today?".

Is there a way to do this with regex? I read somewhere that regex has better performance. I've tried looping thru the array then replacing the characters but I couldnt get it working and my solution would have nested loops due to the given string

CodePudding user response:

Well, this is the simplest I have managed to do.

However, I myself kind of consider it a bad solution.

Let me know if it helps at all...

const myString = "How is your (model: Audi) today?";
const arr = ["(model: Audi)", "(model: Kia)"];

arr.forEach(item => {
  const part = item.match(/\w \)$/)[0];
  const subPart = part.substring(0, part.length - 1);

  if (myString.includes(item))
    console.log(myString.replace(item, subPart));
});

CodePudding user response:

const arr = ["(model: Audi)", "(model: Kia)"];
let string = "How is your (model: Audi) today?";
for (let data of arr){
  string = string.replace(data, data.split(": ")[1].replace(")",""))
}
console.log(string);

  • Related