Friday, July 24, 2009

javascript: function replace and regular expression


Share at Facebook

Today I'm going to tell you how to handle the regex from the function replace() of javascript. It is more or less similar to other scripting language. But still I'm going to provide few sample code chunk with explanation, which may help you.

Lets say that we have a str variable for our all example

// our experimental variable
var str = ' [ EEUa testing 1278 <p> adsUYJJDsa UIU <p> 123 asdasd ] ';


Now you want to remove a certain word from it. It is a simple regular expression. For example removing the test from the string
str = str.replace(/test/, "");
This will just remove the text test from the str, and will replace with empty. You can add g or i after the regex. g for global, means it will replace until all matches are found, and i for case insensitive.

Now if you want to remove all p tags from your string, the regular expression will be simply as below.

// remove p tags
str = str.replace(/<p>/gi, " ");
document.write(str);


Now lets replace all the white spaces from the space, and replace with single space. The regular expression with code will be as below.

// remove multiple spaces
str = str.replace(/\s+/g, " ");
document.write(str);


Now lets trim our str variable. Means to remove the leading and trailing free spaces.

// trim
str = str.replace(/^\s+|\s+$/g, "");
document.write(str);


Lets replace all the numbers from the string.

// remove numbers
str = str.replace(/\d+/g, "");
document.write(str);


Now, finally replace all the capital letters from the string.

// remove all upper case
str = str.replace(/[A-Z]+/g, "");
document.write(str);


You have seen that I have used the i and g modifier of regular expression according to my need. I'll hope that these few code example will help you a bit to understand about the regular expression using from your javascript code.

Thanks,
Wolf




No comments: