Chandrakanth Chandrakanth - 1 year ago 88
Javascript Question

Replaceable string with special characters

I have a string let's say

var str = "blah blah [ID] blah [ID]";

Now, i want to replace "[ID]" and tried as below

str = str.replace("[ID]", "");

however, it replaces only the first occurrence

then, i tried global replacement as below

str = str.replace(/[ID]/g, "");

But, no luck. Please help

Answer Source

[ and ] have special meaning in regular expressions, so they have to be escaped with backslashes:

str = str.replace(/\[ID\]/g, "");