Eanna5
Eanna5

Reputation: 33

How to remove exact word from a string

If I have a string

TestString = "{Item:ABC, Item:DEF, Item:GHI}";

How can I remove all of the "Item:"s. I have tried to use

msg = TestString.replace(/[\Item:/&]+/g, "");

but this unfortunately removes all the Is, Ts. Es and M,s from any letters that may follow.

How can I remove the exact text Thanks!

Upvotes: 2

Views: 14559

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386570

You could use

/Item:/g

for replacing Item:.

The fomer regular expression

/[\Item:/&]+/g

used a character class with single letters instead of a string.

var TestString = "{Item:ABC, Item:DEF, Item:GHI}",
    msg = TestString.replace(/Item:/g, "");

console.log(msg);

Upvotes: 1

Abhinav Galodha
Abhinav Galodha

Reputation: 9878

It should be simple, you can directly create a Regex like /Item:/g,

var TestString = "{Item:ABC, Item:DEF, Item:GHI}";
var msg = TestString.replace(/Item:/g, "");
console.log(msg);

Upvotes: 8

Related Questions