[Solved-5 Solutions] Replace all occurrences of a string in JavaScript - javascript tutorial
Problem:
How to replace all occurrences of a string in JavaScript ?
Solution 1:
Regular Expression Based Implementation
Split and Join (Functional) Implementation
The regular expression based implementation is the faster, but the split and join an implementation to slower. Regular expression based implementation if search have certain characters they are reserved as special characters in regular expressions.MDN also provides an implementation to escape strings. It is standardized as RegExp.escape(str)
.
Call escapeRegExp within String.prototype.replaceAll implementation.
Solution 2:
It response
Simplify
Note: In regular expressions have a special characters to pass an argument in the find
function without any pre-processing it could escape those characters.
replaceAll()
function is modified to the following and also includes escapeRegExp
:
Solution 3:
As an alternative to regular expressions is simple to literal string
General pattern:
This code is used to faster than using replaceAll
.
Solution 4:
Using g
flag set in regular expression to replace all:
Solution 5:
Using string prototype function:
We want escape to find
the special characters: