Saturday, March 14, 2009

JavaScript String Replace All

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...







[code]

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

str = str.replace(/heaven/,”mentor”)



[/code]



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:



[code]

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

str = str.replace(/heaven/g,”mentor”)





[/code]







The output



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

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner

MSDotnetMentor

MSDotnetMentor My Website http://msdotnetmentor.com