totn JavaScript

JavaScript: String replace() method

This JavaScript tutorial explains how to use the string method called replace() with syntax and examples.

Description

In JavaScript, replace() is a string method that is used to replace occurrences of a specified string or regular expression with a replacement string. Because the replace() method is a method of the String object, it must be invoked through a particular instance of the String class.

Syntax

In JavaScript, the syntax for the replace() method is:

string.replace(search_expression, replacement);

Parameters or Arguments

search_expression

It is either a string value or a RegExp object that will be searched for in string. As a RegExp object, it can be a combination of the following:

Value Description
^ Matches the beginning of a string. If used with a match_parameter of 'm', it matches the start of a line anywhere within expression.
$ Matches the end of a string. If used with a match_parameter of 'm', it matches the end of a line anywhere within expression.
* Matches zero or more occurrences.
+ Matches one or more occurrences.
? Matches zero or one occurrence.
. Matches any character except NULL.
| Used like an "OR" to specify more than one alternative.
[ ] Used to specify a matching list where you are trying to match any one of the characters in the list.
[^ ] Used to specify a nonmatching list where you are trying to match any character except for the ones in the list.
( ) Used to group expressions as a subexpression.
\b Matches a word boundary
\B Matches a non-word boundary
{m} Matches m times.
{m,} Matches at least m times.
{m,n} Matches at least m times, but no more than n times.
\n n is a number between 1 and 9. Matches the nth subexpression found within ( ) before encountering \n.
[..] Matches one collation element that can be more than one character.
[::] Matches character classes.
[==] Matches equivalence classes.
\d Matches a digit character.
\D Matches a nondigit character.
\w Matches a word character.
\W Matches a nonword character.
\s Matches a whitespace character.
\S matches a non-whitespace character.
\t matches a horizontal tab character.
\v matches a vertical tab character.
\r matches a carriage return character.
\f matches a form feed character.
\n matches a line feed character.
[\b] matches a backspace character.
\0 matches a NUL character.
*? Matches the preceding pattern zero or more occurrences.
+? Matches the preceding pattern one or more occurrences.
?? Matches the preceding pattern zero or one occurrence.
{n}? Matches the preceding pattern n times.
{n,}? Matches the preceding pattern at least n times.
{n,m}? Matches the preceding pattern at least n times, but not more than m times.
replacement

It is the replacement string or a function (that returns a replacement string). The $ character is a special character that is used in the replacement string to indicate that the value from the pattern match can be used as part of the replacement string. Here are the ways that you can use the $ character:

Value Description
$1, $2 ... $n

Used to insert the substring from a parenthesized match.

$1 is the 1st parenthesized match,
$2 is the 2nd parenthesized match,
...
$n is the last parenthesized match

$& Used to insert the matched substring
\\$ Used to insert the literal $ character
$+ Used to insert the substring from the last parenthesized match
$' Used to insert the string to the right of the matched substring
$` Used to insert the string to the left of the matched substring

Returns

The replace() method returns a string with either the first match or all matches of search_expression replaced with replacement (see example below as the replacement behavior changes depending on the type of search_expression).

Note

  • The replace() method does not change the value of the original string.
  • The replace() method will return different results depending on whether the g attribute was specified. See the example below for an explanation.

Example

Let's take a look at an example of how to use the replace() method in JavaScript.

String as the Search Expression

The simplest way to use the replace() method is to find and replace one string with another string. This method does not involve regular expression objects.

For example:

var totn_string = 'TechOnTheNet is great';

console.log(totn_string.replace('great', 'the best'));

In this example, we have declared a variable called totn_string that is assigned the string value of 'TechOnTheNet is great'. We have then invoked the replace() method of the totn_string to find and replace the first occurrence or match.

We have written the output of the replace() method to the web browser console log, for demonstration purposes, to show what the replace() method returns.

The following will be output to the web browser console log:

TechOnTheNet is the best

In this example, the replace() method performs a search for the first occurrence of the string 'great' and replaces it with the string 'the best'. As you can see, the replace() method returned the string 'TechOnTheNet is the best'.

Regular Expression as the Search Expression (Single Match)

Next, we'll take a look at regular expressions. You can use the replace() method to search for and replace the first occurrence (ie: single match) of a regular expression pattern.

For example:

var totn_string = 'We Want to Replace the First Uppercase Character';

console.log(totn_string.replace(/[A-Z]/, 'Y'));

The following will be output to the web browser console log:

Ye Want to Replace the First Uppercase Character

In this example, the replace() method performs a search for the first occurrence of an uppercase character and replaces that character with 'Y'. The replace() method returns the new string 'Ye Want to Replace the First Uppercase Character' where the 'W' was replaced with 'Y'.

Regular Expression as the Search Expression (Global Match)

You can also use the replace() method to search for all matches of a regular expression pattern. This is done by performing a global match as specified by the g attribute.

For example:

var totn_string = 'We Want to Replace all Uppercase Characters';

console.log(totn_string.replace(/[A-Z]/g, 'Y'));

The following will be output to the web browser console log:

Ye Yant to Yeplace all Yppercase Yharacters

In this example, the replace() method performed a global match and searched for all occurrences of uppercase characters and replaced them with 'Y'. This was done by specifying the g attribute at the end of the regular expression.

This time the replace() returned the new string 'Ye Yant to Yeplace all Yppercase Yharacters'.