faqts : Computers : Programming : Languages : JavaScript : Language Core : Regular Expressions

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

33 of 56 people (59%) answered Yes
Recently 3 of 10 people (30%) answered Yes

Entry

How do I search and replace text using regular expressions?
How can I change certain portions of text input, for example to reformat a text entry?
How can I replace a specific part of any given string?

Sep 9th, 2000 17:21
Rey Nuņez,


One of the more powerful uses of regular expressions is in search and 
replace operations, where a pattern is matched and then replaced with 
new text. This is easily accomplished using the string.replace() 
method. 

The example below shows how all instances of a given word or phrase can 
be replaced with another given word or phrase using the string.replace
() method. 

<script language="JavaScript1.2">
<!--
function replaceMe(str, chg) {
var pattern = new RegExp (str,'ig');
return str.replace( pattern, chg);
}
//-->
</script>

To test, type some text containing the word or phrase to search for in 
the first text box, and the replace text in the second. 

<div align="center">
<form onsubmit="find.value=replaceMe(find.value, repl.value);return 
false;">
<table cellpadding=10 cellspacing=0 border=0 bgcolor="khaki">
<tr>
  <td>Search for:<br><input name="find"></td>
  <td>Replace with:<br><input name="repl"></td></tr>
<tr>
  <td colspan=2 align="center"><input type="submit" 
value="Replace"></td></tr>
</table></form></div>

Note that the sample above makes use of the i and g modifiers to 
establish a case-insensitive global search.