Wednesday, February 24, 2010

JavaScript replaceAll - replace all occurrences of a string with new string

During string replace, JavaScript replace() function replaces only the first occurence of the match. Use Regular Expression match to replace all the occurrences of the specified string. Regular Expression match can be specified by providing a "g" next to it, as shown below.

var stringVariable = "This message is a warning message";
alert(stringVariable.replace("message", "alert"));
//shows "This alert is a warning message"

alert(stringVariable.replace(/message/g, "alert"));
//shows "This alert is a warning alert"


No comments:

Post a Comment