How to Use the String.prototype replace Method in JavaScript

  • 6 min read
  • December 6, 2020
linkedin twitter facebook reddit
linkedin twitter facebook reddit

The replace() method operates on a String, returning a new string with the specified changes.

Note: JavaScript strings are immutable. This means that a new string is created in memory for the return value of replace().

Syntax

The syntax of replace() is as follows:

const newStr = str.replace(pattern, newValue)

  • pattern: The pattern to replace. This can be either a String or a regular expression.

If the pattern is a String, only the first matching portion of the string is replaced – other instances of the pattern in the string will not be affected.

  • newValue: The value to replace the specified pattern with. This can be either a String or a function.

When newValue is a function, it will be invoked for each match in the string (see the relevant section below).

String.prototype.replace() Examples

Below are a few examples that demonstrate the functionality of the String.prototype.replace() method. The first example below demonstrates the most basic usage of the method:

const str = 'Hello my name is Don and I am a web developer';
const res = str.replace('web', 'software');
console.log(res);
// Expected output: Hello my name is Don and I am a software developer

In the example above, the word ‘web’ is the pattern to be replaced. ‘software’ is the newValue. The replace() method finds the first instance of the pattern (web) in the source string, and replaces it with the newValue parameter (software). The end result is that “web” is replaced with “software” in the string, resulting in a new string: “Hello my name is Don and I am a software developer”.

It is not necessary to limit your replace pattern argument to words alone – any pattern can be replaced:

const mess = str.replace('am', 'ain\'t');
console.log(mess);
// Expected output: Hello my nain'te is Don and I am a web developer

This example results in a string that is a bit messy, and also highlights the limitation of using a string pattern to specify the characters to replace. As the pattern we passed in (am) is a String, only the first instance of the pattern is replaced – this first instance is found in the word name.

Note: The backslash (\) character in the code enables us to use special characters in our strings. Without it, the above code would produce a Syntax Error as the single quote after the “n” would otherwise indicate the end of the input string. In this case, the remaining “t” at the end of the string would have no meaning in JavaScript, resulting in the error being thrown.

The above example, because it used a string, only replaced the first instance of the pattern found. To instead change all of the matching patterns, you must use a regular expression (RegEx).

In short, regular expressions are objects which can be used to detect patterns in string input:

const stillAMess = str.replace(/am/g, 'ain\'t');
console.log(stillAMess);
// Expected output: Hello my nain'te is Don and I ain't a web developer

In the example above, the pattern parameter receives a RegEx as its value. The RegEx is specified using two slashes (/) surrounding the desired search pattern (am). The final character in the pattern (“g”) occurs after the closing slash of the RegEx and is a flag indicating that the RegEx pattern should be used to perform a global search of the string, resulting in matching multiple instances of the provided pattern.

Note: RegExes are widely used by developers. If you are not familiar with RegExes, you should review them by reading the information at this link.

While the above call to replace() catches all the instances of the desired pattern (am), the result is still not particularly readable. This is due to the search pattern searching for instances of am wherever they are found, instead of replacing only the word form of the pattern as we may have originally desired. We can solve this by adding a space to our search pattern, either before the “a” character or after the “m” character. This will limit our search to only versions of the pattern that have a leading or trailing space, giving us the change we are looking for.

Note: Make sure to add a space in the corresponding location of the newValue argument, or else the replace() method will replace the corresponding space as well.

const correct = str.replace(/am /g, 'ain\'t ');
console.log(correct);
// Expected output: Hello my name is Don and I ain't a web developer

In the above example, a space was added after the “m” character, as well as after the “t” character in the newValue parameter. This results in the word “am” being replaced by the word “ain’t” in the return value.

How to use a function for the newValue parameter

Let’s demonstrate using a function as the newValue parameter by implementing a very simple encryption mechanism. The following code will take each letter in the const str and replace it with a different character or special character using the characters’ Unicode codes:

const str = 'Hello my name is Don and I am a web developer';
const encrypt = str.replace(/[a-zA-Z]/g, function (char) {
    let i = char.charCodeAt() + 5;
    return String.fromCharCode(i);
})
console.log(encrypt);
// Expected output: Mjqqt r~ sfrj nx Its fsi N fr f |jg ij{jqtujw

In the above example, the pattern parameter received a RegEx argument, telling the replace() method to search for any character in the range a to z, whether the character is lowercase or uppercase. The “g” is again used to indicate a global search; without it, only the first character of the original string will be replaced.

The newValue parameter received a function which does the following:

For every character in the string, let i is declared and assigned the value of the character’s Unicode code value + 5 (note – this is a numeric value). The character’s Unicode value is retrieved using the charCodeAt() method.

The function returns a character using the calculated value with the fromCharCode() method, which converts an integer Unicode value (or any other number of significance) into its corresponding character. This value is then returned from the function, replacing the original character in the source string.

To explore this further, let’s look at what happens to the first character in the string – “H”:

console.log('H'.charCodeAt()); //Expected output: 72
console.log(String.fromCharCode(77)); //Expected output: M
console.log('M'.charCodeAt()); //Expected output: 77

In the example above, we start by retrieving the value of the first letter in const str – “H”. The value of “H” in Unicode is 72. By adding 5 to this value, we get the new Unicode value of 77. When this value is provided to fromCharCode(), that function returns the Unicode character with a code value of 77 – in this case, the letter “M”.

 

Related Articles

JavaScript – How to Replace a Whole String

JavaScript – How to Change The Page URL

JavaScript – How to Use the toLowerCase() Method

Related Posts

How to Change CSS Using JavaScript

How to Change CSS Using JavaScript

Cascading Style Sheets (CSS) is used to design the layout of a webpage. CSS is a set of structured rules describing the layout of elements in

How to Use the Assignment Operator in JavaScript

How to Use the Assignment Operator in JavaScript

The Assignment operator is used to assign a value to a variable. Assignment (=) The assignment operator simply assigns the value of the right operand to

How to Use the for…in Statement in JavaScript

How to Use the for…in Statement in JavaScript

The for…in statement is used to loop through an object’s properties. Basic for…in loop example The following code demonstrates a basic example using the for…in statement