|
| JAVASCRIPT replace() METHOD
The replace() method replaces a set of characters in a string with another set of characters. The replace() method is case sensitive.
The replace() method takes two compulsory arguments: the string or character tosearchfor and replacewith. Always remember that the first position always starts at 0 (and not 1). The replace() method returns the original string if no occurrence is found, else it returns the the string with the new replacement.
The general format is:
string.replace(/tosearchfor/, replacewith);
Please note:
The tosearchfor argument must be enclosed in two forward slashes like: /tosearchfor/
By default, the replace() method is case sensitive. To make it case insensitive place an i after the second forward slash like:
string.replace(/tosearchfor/i, replacewith);
By default, the replace() method is only finds and replaces one occurrence of a match. For replacement of all matches, place a g (for global search) after the second forward slash like so:
string.replace(/tosearchfor/g, replacewith);
Example: Default Replace - case sensitive, replaces only one occurrence
<script type="text/javascript">
var string="The brown box is brown";
document.write(string.replace(/brown/, "red"));
</script>
The above will output:
Example: Global Replace - case sensitive, replaces all occurrences
<script type="text/javascript">
var string="The brown box is brown";
document.write(string.replace(/brown/g, "red"));
</script>
The above will output:
Example: Case Insensitive Replace Only - case insensitive, replaces one occurrence
<script type="text/javascript">
var string="The Brown box is brown";
document.write(string.replace(/brown/i, "red"));
</script>
The above will output:
Example: Case Insensitive And Global Replace - case insensitive, replaces all occurrences
<script type="text/javascript">
var string="The Brown box is brown";
document.write(string.replace(/brown/gi, "red"));
</script>
The above will output:
See Also:
|
|