Here's a simple regular expression search and replace in Javascript (for JScript, replace alert with WScript.Echo). I wrote it as a test for another script to modify a configuration file.
var s1 = "Hello World" var s2 = s1.replace(/Hello/, "Goodbye") alert(s1 + "," + s2) var s3 = s1.replace(/(Hello)/, "$1 Googly") alert(s1 + "," + s3)
If you run this script in a Web page, you should see the first alert dialog containing "Hello World,Goodbye World" and a second alert dialog containing "Hello World,Hello Googly World".
In this example, the parentheses (()) enclose a match pattern and the dollar ($) symbol represents the matched string (i.e. $1 is the first matched string, $2 is the second matched string, etc.).
No comments:
Post a Comment