[thelist] Use of "replace" method in JavaScript

Simon Dell simondl at epic.co.uk
Mon Jan 21 03:38:36 CST 2002


Syed,

The replace function is a method of the String object.

      string.replace(regExpr,newString)

where regExpr is either a quoted string ("a string") or a regular 
expression (/pattern/) and newString is a string.

The replace method searches the string for a piece of text which matches 
regExpr (either a direct match for the string or a pattern match when using 
a regular expression). For more information on regular expressions, try 
this tutorial:
http://www.webreference.com/js/column5/index.html

So
"John went to the historical city of Lahore for spending 
vacation.".replace("historical city of Lahore","beautiful city of Swat")
will do what you want, but it's not very flexible.

I hope that's helpful,
Simon



At 14:09 21/01/02 +0500, you wrSote:
>Hi,
>Thank you for taking time to reply.
>In fact, I want to replace a part of a sentence with some other words and 
>that sentence is stored in a variable. Look at the
>following code:
><script language="JavaScript">
>var sentence="John went to the historical city of Lahore for spending 
>vacation."
>// I want to change the value of variable "sentence" as in following line 
>by using "replace" method.
>sentence="John went to the beautiful city of Swat for spending vacation."
>// I have replaced "historical city of Lahore" with "beautiful city of 
>Swat" by simple means. I want to do the same with the help of
>"replace" method.
></script>
>I hope you can help.
>Thank you,
>Syed Zeeshan Haider.
>http://syedzeeshanhaider.faithweb.com/





More information about the thelist mailing list