Ads by Lake Quincy Media
| Next Tip?
Home » Javascript

Replacing string : Using Java Script

14 March 2009 1,507 views No Comment
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

JavaScript String Replace All

Today When I was working I came across the need to replace all the “’” marks with null or with nothing like “” as the “’” mark produces an error while handling with database I have the StringBuldier Class and could replace all at once but to use that it will be a server side code that means irrespective of anything on textchanged event the page should be postback so I decided to use the JavaScript function replace ()

Now the problem with this JavaScript String Replace function is that it replaces the first occurrence in the string. It takes two simple parameters. The first parameter is the pattern to find and the second parameter is the string to replace the pattern with when found. The JavaScript function does not Replace All…

str=”http://www.msdotnetheaven.com and http://www.msdotnetheaven.com”;
str = str.replace(/heaven/,”mentor”)

The output :

str=”http://www.msdotnetmentor.com and http://www.msdotnetheaven.com”;

To make the replace function of the JavaScript to replace all the occurrences of the matched string we have to apply a trick and the trick is, use the g modifier like this:

str=”http://www.msdotnetheaven.com and http://www.msdotnetheaven.com”;
str = str.replace(/heaven/g,”mentor”)

The output:

str=”http://www.msdotnetmentor.com and http://www.msdotnetmentor.com”;

Popularity: 2%

Post to Twitter Tweet This Post

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

Ads by Lake Quincy Media

Leave your response!

You must be logged in to post a comment.

Get Adobe Flash playerPlugin by wpburn.com wordpress themes