0 (0|0)

Javascript Replace All Instances In a String

    There is a replace function to change some character in a string. You can replace the defined instances or some constructions using regular expressions. To change all instances in a string it is necessary to set the defined flag g in a regular expression.

Replace All Spaces

Space character in the regular expressions is \s. If there is more than one space in one place in a string the construction of regex will be \s+. Like it was said earlier to change all instances of space there should be flag g in the regular expression.
var str = ‘This is a simple string’;
var charYouWant = ‘’;
str.replace(/\s+/g, charYouWant);

ReplaceAll Function

Using prototype property you can do everything you want with the objects in javascript.

String.prototype.replaceAll = function(needle, replaceTo)
 var str = this.replace(new RegExp(needle, 'g'), replaceTo);
  return str;
This function returns a string. But the original function will not be changed.

To replace all spaces in a string using replaceAll function you should do the next:
var newString = str.replaceAll(‘ ’, charYouWant);

Added 12.10.2012
By Sergej
sds said
Added: 17.02.2015 16:21:08
Your name
Add comment
Don't miss:
Most popular
The best

Web development 2011-2012 ©