2

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!

Eanna5
  • 33
  • 1
  • 1
  • 4
  • 3
    Possible duplicate of [Javascript how to remove text from a string](http://stackoverflow.com/questions/10398931/javascript-how-to-remove-text-from-a-string) – Tha'er AlAjlouni ثائر العجلوني Jan 19 '17 at 21:46
  • 1
    Assuming its valid JavaScript, you could use `JSON.parse` and `Object.values`. Note that your example is not valid JSON, but if its from a trusted source you could use `eval` in place of `JSON.parse`. – Jared Smith Jan 19 '17 at 21:46
  • I did look at that thread. And when I used it I found it to be removing the the letters any time they came up and were not part of Item – Eanna5 Jan 19 '17 at 21:56

2 Answers2

8

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);
Abhinav Galodha
  • 9,293
  • 2
  • 31
  • 41
1

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392