0

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.

2 Answers 2

2

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

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

Comments

1

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

4 Comments

@ftk789 I have updated the code with a check for the matched value in the array.
Your code is leaving some square brackets in, the OP seemed to want to remove exactly what was in his array (including the brackets)
@AdamPearson Exactly what i wanted, But Thank you very much for the answer as well, I appreciate it.
@AdamPearson Ow yes, the match should not be indexed.

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.