Home > Enterprise >  How to remove an array value from a string in Javascript
How to remove an array value from a string in Javascript

Time:01-11

Straight forward, How to remove an array value from a string, Example:

var String = "Hi my name is ftk: [2] what is yours? [ And how are 2 5 you? [1] Are you ok?"
var array = [ "[1]", "[2]" ]

---OUTPUT---

"Hi my name is ftk: what is yours? [ and how are 2 5 you? Are you ok?"

Basically I want to remove a specific array and only when it's exactly the same word, If it makes sense.

I have tried .replace with global, But I couldn't use an array there, I can only input a specific string like:

var string2 = string.replace(/\[1|\]/g, '');

See above, I can't remove 2 words at the same time, And it would really suck to manually create a new var to it eachtime I add a specific word to remove, So an Array would be the best.

Thanks in Advance.

CodePudding user response:

You can just loop through your array, replacing each array item as you go:

let string = "Hi my name is ftk: [2] what is yours? [ And how are 2 5 you? [1] Are you ok?"
let array = [ "[1]", "[2]" ]


for (let i = 0; i < array.length; i  ) {
    string = string.replace(array[i], '');
}

console.log(string);

CodePudding user response:

You might use a character class to define multiple matches to remove. Then in the callback of replace, check if the match occurs in the array.

\[[12]]

Example

var string2 = string.replace(/\[[12]]/g, '');

var string = "[3] Hi my name is ftk: [2][2] what is yours? [ And how are 2 5 you? [1] Are you ok?"
var array = ["[1]", "[2]"];
var string2 = string.replace(
  /\[[12]]/g,
  m => array.includes(m) ? '' : m
);
console.log(string2);

  • Related