I have strings with extra whitespace characters. Each time there's more than one whitespace, I'd like it be only one. How can I do this using JavaScript?
-
2remove duplicate whitespace from the end/beginning, or anywhere in the text?ninjagecko– ninjagecko2011-05-28 17:24:54 +00:00Commented May 28, 2011 at 17:24
-
1Possible duplicate of Regex to replace multiple spaces with a single spaceMuhammad Omar ElShourbagy– Muhammad Omar ElShourbagy2017-08-08 15:33:29 +00:00Commented Aug 8, 2017 at 15:33
12 Answers
Something like this:
const str = " a b c "
const result = str.replace(/\s+/g, ' ').trim()
console.log('result', result)
console.log('result.length', result.length)
10 Comments
You can augment String to implement these behaviors as methods, as in:
String.prototype.killWhiteSpace = function() {
return this.replace(/\s/g, '');
};
String.prototype.reduceWhiteSpace = function() {
return this.replace(/\s+/g, ' ');
};
This now enables you to use the following elegant forms to produce the strings you want:
"Get rid of my whitespaces.".killWhiteSpace();
"Get rid of my extra whitespaces".reduceWhiteSpace();
1 Comment
Here's a non-regex solution (just for fun):
var s = ' a b word word. word, wordword word ';
// with ES5:
s = s.split(' ').filter(function(n){ return n != '' }).join(' ');
console.log(s); // "a b word word. word, wordword word"
// or ES2015:
s = s.split(' ').filter(n => n).join(' ');
console.log(s); // "a b word word. word, wordword word"
Can even substitute filter(n => n) with .filter(String)
It splits the string by whitespaces, remove them all empty array items from the array (the ones which were more than a single space), and joins all the words again into a string, with a single whitespace in between them.
1 Comment
using a regular expression with the replace function does the trick:
string.replace(/\s/g, "")
2 Comments
I presume you're looking to strip spaces from the beginning and/or end of the string (rather than removing all spaces?
If that's the case, you'll need a regex like this:
mystring = mystring.replace(/(^\s+|\s+$)/g,' ');
This will remove all spaces from the beginning or end of the string. If you only want to trim spaces from the end, then the regex would look like this instead:
mystring = mystring.replace(/\s+$/g,' ');
Hope that helps.
1 Comment
'' instead of ' '.jQuery.trim() works well.
1 Comment
I know I should not necromancy on a subject, but given the details of the question, I usually expand it to mean:
- I want to replace multiple occurences of whitespace inside the string with a single space
- ...and... I do not want whitespaces in the beginnin or end of the string (trim)
For this, I use code like this (the parenthesis on the first regexp are there just in order to make the code a bit more readable ... regexps can be a pain unless you are familiar with them):
s = s.replace(/^(\s*)|(\s*)$/g, '').replace(/\s+/g, ' ');
The reason this works is that the methods on String-object return a string object on which you can invoke another method (just like jQuery & some other libraries). Much more compact way to code if you want to execute multiple methods on a single object in succession.
var x = " Test Test Test ".split(" ").join(""); alert(x);
1 Comment
How about this one?
"my test string \t\t with crazy stuff is cool ".replace(/\s{2,9999}|\t/g, ' ')
outputs "my test string with crazy stuff is cool "
This one gets rid of any tabs as well
2 Comments
\s. Unnecessarily complex regex, might as well just write /\s+/g.{2,}. The 9999 is unnecessary and even potentially wrong. I'm not sure if only matching and replacing 2 or more spaces is beneficial or detrimental to the performance.If you want to restrict user to give blank space in the name just create a if statement and give the condition. like I did:
$j('#fragment_key').bind({
keypress: function(e){
var key = e.keyCode;
var character = String.fromCharCode(key);
if(character.match( /[' ']/)) {
alert("Blank space is not allowed in the Name");
return false;
}
}
});
- create a JQuery function .
- this is key press event.
- Initialize a variable.
- Give condition to match the character
- show a alert message for your matched condition.