So i'm writing a tiny little plugin for JQuery to remove spaces from a string. see here
(function($) {
$.stripSpaces = function(str) {
var reg = new RegExp("[ ]+","g");
return str.replace(reg,"");
}
})(jQuery);
my regular expression is currently [ ]+
to collect all spaces.
This works.. however It doesn't leave a good taste in my mouth..
I also tried [\s]+
and [\W]+
but neither worked..
There has to be a better (more concise) way of searching for only spaces.
This question is related to
javascript
regex
This works just as well: http://jsfiddle.net/maniator/ge59E/3/
var reg = new RegExp(" ","g"); //<< just look for a space.
This is used in several apps to clean user-generated content removing extra spacing/returns etc but retains the meaning of spaces.
text.replace(/[\n\r\s\t]+/g, ' ')
str.replace(/\s/g,'')
Works for me.
jQuery.trim
has the following hack for IE, although I'm not sure what versions it affects:
// Check if a string has a non-whitespace character in it
rnotwhite = /\S/
// IE doesn't match non-breaking spaces with \s
if ( rnotwhite.test( "\xA0" ) ) {
trimLeft = /^[\s\xA0]+/;
trimRight = /[\s\xA0]+$/;
}
"foo is bar".replace(/ /g, '')
Remove all spaces in string
// Remove only spaces
`
Text with spaces 1 1 1 1
and some
breaklines
`.replace(/ /g,'');
"
Textwithspaces1111
andsome
breaklines
"
// Remove spaces and breaklines
`
Text with spaces 1 1 1 1
and some
breaklines
`.replace(/\s/g,'');
"Textwithspaces1111andsomebreaklines"
Source: Stackoverflow.com