Copyright © tutorialspoint.com

Javascript String - replace() Method

previous next

Advertisements


Description:

This method finds a match between a regular expression and a string, and replaces the matched substring with a new substring.

The replacement string can include the following special replacement patterns:

PatternInserts
$$ Inserts a "$".
$&Inserts the matched substring.
$` Inserts the portion of the string that precedes the matched substring.
$'Inserts the portion of the string that follows the matched substring.
$n or $nnWhere n or nn are decimal digits, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object.

Syntax:

string.replace(regexp/substr, newSubStr/function[, flags]);

Here is the detail of parameters:

Return Value:

Example:

Following example shows how to use the global and ignore case flags which permits replace to replace each occurrence of 'apples' in the string with 'oranges'.

<html>
<head>
<title>JavaScript String replace() Method</title>
</head>
<body>
<script type="text/javascript">

var re = /apples/gi;
var str = "Apples are round, and apples are juicy.";
var newstr = str.replace(re, "oranges");

document.write(newstr ); 

</script>
</body>
</html>

To understand it in better way you can Try it yourself.

Example:

Following example shows how to switch words in a string:

<html>
<head>
<title>JavaScript String replace() Method</title>
</head>
<body>
<script type="text/javascript">

var re = /(\w+)\s(\w+)/;
var str = "zara ali";
var newstr = str.replace(re, "$2, $1");
document.write(newstr);

</script>
</body>
</html>

To understand it in better way you can Try it yourself.


previous next

Copyright © tutorialspoint.com