Sunday, December 27, 2009

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.


No comments:

Get function name programaticaly - Python

This little piece of code will help you to get the function name programatically. This is very helpful when you are implementing the debug...