Thursday, 17 March 2011

JavaScript replace() Method

The replace() method searches for a match between a substring (or regular expression) and a string, and replaces the matched substring with a new substring

Syntax

string.replace(regexp/substr,newstring)

Both are required arguments.

To replace all matches with the newstring it is better to use the regular expression version of it. string.replace(substr,newstring) replaces only the first match. But string.replace(/regexp/g,newstring) replaces all matches with newstring. Also you can do case-insensitive replace using regexp i.e. string.replace(/regexp/gi,newstring)

<script type="text/javascript">

var str="I enjoy scripting"; //Not really!!!

//Following script will do a case-insensitive search for the string "enjoy" in the var str and will replace all occurances with "hate"

document.write(str.replace(/enjoy/gi, "hate"));

//And the output will be "I hate coding"

//Following script will do a global search for spaces in the var str and replaces them with non-breaking spaces.

document.write(str.replace(/ /g, "&nbsp;"));


//The output will be "I&nbsp;enjoy&nbsp;coding"

</script>

No comments:

Post a Comment