JavaScript String Replacement: Simple Text & Regex
Replacing text in JavaScript is one of the most common string manipulation functions you can perform, thanks to the replace()
method available in the String
prototype.
Simple String Replacement
The most common use-case for replacing text in JavaScript is using the replace()
method, which accepts a substring argument to match against an existing string, and a replacement string as the second argument:
var old_str = "Welcome to Orangeable";
var new_str = old_str.replace("Orangeable", "orange");
console.log(new_str);
// Welcome to orange
The above method replaces the text "Orangeable" with "orange".
Strings in JavaScript are immutable, meaning that once they are created, they can never be changed. When using the replace()
method, you're actually creating a brand new string, not updating the existing one.
Chaining String Replace Operations
You can also perform multiple string replace operations by chaining the replace()
method:
var old_str = "Welcome to Orangeable";
var new_str = old_str
.replace("Orangeable", "orange")
.replace("Welcome", "Eat")
.replace("to", "my");
console.log(new_str);
// Eat my orange
Regular Expression Match
Matching an exact substring can be useful, but there may be times when we need to match a pattern within a string instead. This can be easily accomplished by replacing strings using regular expressions:
var old_str = "Welcome to Orangeable";
var new_str = old_str.replace(/o/gi, "a");
console.log(new_str);
// Welcame ta arangeable"
In this example, we searched for every occurrence of the letter "o", and replaced it with a lowercase "a", giving us a nonsense greeting message in return.
We used two regular expression flags to match the substring:
g
: global - matches all occurrences within a substring. Omitting this flag will only match the first occurrence in the substring.i
: case-insensitive - matches all occurrences within a substring, regardless of case. Omitting this flag will only match occurrences of the same case.
Regex Backreference
Using a regex backreference like $&
allows you to include the matched string in the replacement string:
var old_str = "Welcome to Orangeable";
var new_str = old_str.replace("Orangeable", "$& $&");
console.log(new_str);
The result leaves us with a sentence that doesn't make much sense but is a great example to show you how the regular expression backreference works.
Other backreference methods include the following:
$'
: Insert the part of the string that's before the matched string.'$
: Insert the part of the string that's after the matched string.$n
: Insert the nth match.
Conclusion
This article taught you how to complete some common text replacement methods, including using plain text and regular expression replacements. You also learned a bit about the regex backreference and how to utilize it in a real-world scenario.
Created: April 04, 2021
Comments
There are no comments yet. Start the conversation!