-1

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

2
  • Show us what you have tried to do so far. Commented May 9, 2022 at 19:33
  • If they all match that pattern, do you need the array at all? "How is your (model: Audi) today?".replace(/\([^:]+:\s([^\)]+)\)/, '$1') Commented May 9, 2022 at 20:43

2 Answers 2

2

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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));
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.