JAVASCRIPT

 Home  Computers & Internet  Web Programming JAVASCRIPT
What is Javascript?
Javascript Placement
Syntax
Reserved Words
Variables
Data Types
Escaping Characters
Concatenation
Arithmetic Operators
Assignment Operators
Comparison Operators
Boolean Operators
Conditional Operator
If Statements
Else If Statements
If Else Statements
Switch Statements
While Loops
For Loops
Do While Loops
Break Statement
Continue Statement
prompt()
alert()
Date()
Event Handlers
String Object Methods
Math Object Methods
Window Object Methods
Arrays

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:

anchor() big()
blink() bold()
charAt() charCodeAt()
concat() fixed()
fontcolor() fontsize()
fromCharCode() indexOf ()
italics () lastIndexOf()
link() match()
replace () search()
slice() small()
split() strike()
sub() substr()
substring() sup()
toLowerCase() toUpperCase()
toSource() valueOf ()

Home | Privacy Policy | Terms Of Use | Contact Us