Learn how to replace all the occurrences of a string in javascript. We will use different approaches to do this.
Using split() and join() functions.
split() function is used to split the string at given expression into an array. It does not includes the expression in the array.
let str = 'I am prashant yadav'; str.split(' '); // splitting at white space ['I', 'am', 'prashant', 'yadav']
We can use regular expressions as well to split the string.
join() function is used to join an array with given expression to create a string.
let strArr = ['I', 'am', 'prashant', 'yadav']; strArr.join(' '); // joining with white space 'I am prashant yadav';
Using both we can replace all / any occurrences of characters in the string.
let str = 'I am prashant yadav'.split('prashant').join('golu'); console.log(str); // 'I am golu yadav'
This method is slow as we are using two different functions.
Using regular expressions
replace() function is used to replace all / any occurrence of characters in the string in javascript.
syntax
String.replace(/EXPR/g, ''); //case sensitive String.replace(/EXPR/gi, ''); //case insensitive
It uses two parameters, first what needs to be replaced and second with whom.
Replace case sensitive string
let str = 'String first, string second'.replace(/string/g, 'random'); console.log(str); // 'String first, random second'
Replace case in-sensitive string
let str = 'String first, string second'.replace(/string/gi, 'random'); console.log(str); // 'random first, random second'
Regular expression efficiency depends upon its implementation so in some cases it can run fast and in some cases it can run slow also they do not perform good with some special characters so it is better to escape them.
let escapeString = (string) => { return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); }
learn more about the =>
functions here.