How to Replace With Regex in JavaScript
Sometimes, we want to replace particular words in a string or write a regular expression (also known as regex) to replace a pattern with a new value.
For that, we can get the advantage of the replace()
function if we have a small string or can use the RegExp
object’s methods to find a pattern in a long string (paragraphs) and replace it with new words/values.
Use of replace()
Function in JavaScript
The replace()
function searches for a string and replaces it with a new string without changing the original string. This function replaces the first match and then stops.
It is why we use regular expressions to meet our needs for validating text and searching through text. We can perform a global, multiline, or case-insensitive match using regex to replace the string.
Example Code:
let p = 'Hello JavaScript World, I am diving into the javascript world.'
console.log(p.replace('JavaScript', 'Python'));
Output:
"Hello Python World, I am diving into the javascript world."
In the output given above, we can observe that the replace()
function stops after replacing the first match. This limitation leads to regular expressions with modifiers, also known as flags.
Replace With Regex (Regular Expression) in JavaScript
We use the i
flag to search with case-insensitivity, which means World
and world
are the same. The test()
method checks and returns true
if the pattern exists.
Example Code:
let p = 'Hello JavaScript World, I am diving into the javascript world.'
const pattern = /javascript/i;
if (pattern.test(pattern)) {
let result = p.replace(pattern, 'Python');
console.log(result);
}
Output:
"Hello Python World, I am diving into the javascript world."
See, the first JavaScript
word is replaced with Python
, although we were trying to match lower-case javascript
. It’s because of the i
flag, but it also stops after the first match.
Now, what if we have more than one sentence or string? We use the g
modifier that performs a global match and replaces all matching words/patterns.
Example Code:
let p =
'Hello JavaScript World, I am diving into the javascript world. It was good to learn JavaScript.'
const pattern = /JavaScript/g;
if (pattern.test(pattern)) {
let result = p.replace(pattern, 'Python');
console.log(result);
}
Output:
"Hello Python World, I am diving into the javascript world. It was good to learn Python."
Remember, the g
flag does a case-sensitive match. It’s why javascript
is not replaced in the above output.
We can use the i
flag with the g
flag if we want to replace that also. Take a look at the following code.
let p =
'Hello JavaScript World, I am diving into the javascript world. It was good to learn JavaScript.'
const pattern = /JavaScript/gi;
if (pattern.test(pattern)) {
let result = p.replace(pattern, 'Python');
console.log(result);
}
Output:
"Hello Python World, I am diving into the Python world. It was good to learn Python."
What if we have a single string spread on multiple lines? Here, the m
flag comes into the action and does a multiline match.
The m
flag not only matches at the start using ^
and the end of each line using the $
symbol, but it can also match the start/end of a line.
Example Code:
let p = `1.JavaScript\n
2.Python
3.Java.`
const pattern = /^\d/mg;
if (p.match(pattern)) {
let result = p.replace(pattern, 'ListItem');
console.log(result);
}
Output:
ListItem.JavaScript
ListItem.Python
ListItem.Java.
If we remove the m
flag from the above example, it will only replace the pattern on the first line (see the following code).
let p = `1.JavaScript\n
2.Python
3.Java.`
const pattern = /^\d/g;
if (p.match(pattern)) {
let result = p.replace(pattern, 'ListItem');
console.log(result);
}
Output:
ListItem.JavaScript
2.Python
3.Java.
Using the following sample code, we can see that it is also possible to find patterns at the end of each line and replace them with the desired value.
let p = `1.JavaScript 1\n
2.Python 2
3.Java 3`;
const pattern = /\d$/gm;
if (p.match(pattern)) {
let result = p.replace(pattern, 'ListItem');
console.log(result);
}
Output:
1.JavaScript ListItem
2.Python ListItem
3.Java ListItem
Till now, we have studied the literal notation of regex. This notation is used when we know that the pattern will remain constant.
Otherwise, it is good to use the constructor function if we suspect that the pattern will be changed. Following is an example of the constructor function.
let p =
'Hello JavaScript World, I am diving into the javascript world. It was good to learn JavaScript.';
const pattern = new RegExp('\javascript', 'gi');
console.log(p.replace(pattern, 'Python'));
Output:
"Hello Python World, I am diving into the Python world. It was good to learn Python."