Menu ▼



Posted By :
avatarmrkraju
Total Views : 959

JavaScript replaceAll function to replacing all occurrences of a string

JavaScript replace() method will replace only the first occurrence of the string. If you want to replace all the occurrences of a string then you have to write your custom code. By using JavaScript regular expressions or by JavaScript array split and join we can replace the all occurrences of spaces, characters, commas or the given input. Lets see how to do that with below examples.

Replace all spaces in a string

var input:'Hello h o w Ar e you?'
input = input.replace(/ /g,'');

Output
//'HellohowAreyou?'


Replace all commas in a string

var input:'Hello, Welcome, to, dotnet,learners,.com'
input = input.replace(/,/g,'');

Output
//'Hello Welcome to dotnetlearners.com'


Replace all occurrences of specific word in a string
Below example will replace all occurrences of the word 'and'

var input:'Example and to and replace and all and the and occurrences and of and a and specific and word'
input = input.replace(/and/g,'');

Output
//'Example to replace all the occurrences of a specific word'


JavaScript function to replace all occurrences of a string


function replaceAll(input, replace, replacewith) {
    return input.replace(new RegExp(replace, 'g'), replacewith);
}

Usage
var input:'Example and to and replace and all and the and occurrences and of and a and specific and word'
replaceAll(input, 'and', '');


Replace all occurrences using JavaScript array split and join.


function replaceAll(input, replace, replacewith) {
    return input.split(replace).join(replacewith);
}

Usage
var input:'Example and to and replace and all and the and occurrences and of and a and specific and word'
replaceAll(input, 'and', '');


Note
Even in JQuery there is no replaceAll function to replace all the occurrences of a string. So you have to use any one of the above JavaScript approach.






comments powered by Disqus


Search dotnetlearners.com