Tuesday, July 13, 2010

The replace() method for Strings

String theory?Image by trailfan via Flickr
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. It searches the string on which it is called for matches.

If the g flag is set, the method replaces all matches in the string with the replacement string; otherwise it replaces only the first match it finds.

EXAMPLES

//replaces first match
//wasit a rat i saw
var s = 'was it a rat i saw'; alert(s.replace(/[ ]/, ''))

//replaces all matches
//wasitaratisaw
var s = 'was it a rat i saw'; alert(s.replace(/[ ]/g, ''))
Enhanced by Zemanta

No comments: