Chandrakanth Chandrakanth - 2 years ago 101
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, "");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download