Javascript: Replace all using REGEX for a string

Using the replace() function under the string object, you can easily perform the regular expression operation to replace a string.

The replace() function from javascript supports the Perl's s/// operation. You can pass the modifier /g for replace all, and /i for case insensitive.

Lets consider the below example code block. This will remove anything inside the <...> tags. Since i'm using the /g modifier after the regex, it will be used as replace all tags from the string


// initial string
var str = "<a ...>hello</a> and <ul ...>bla bla</ul>";
// remove any tags from the above string
str = str.replace(/<.*?>/g, "");


Remember, if you remove the /g at the end of the regex, it will only remove the first tag from sample string. Also once again you can use /i modifier to ignore case sensitivity.

Cheers!!
Wolf

Comments