Reputation: 328
I'm trying to format the input of a user into single spaces because I will use the input to compare the strings in the results. The problem is the compare function only works in single spaces, so when a user accidentally added some extra spaces or press enter it will not work.
here's my regex and code plus a fiddle:http://jsfiddle.net/purmou/eSE9Y/
html
<textarea id="input"></textarea>
<button>Submit</button>
javascript
$("button").click(function(){
$('#input').val($('#input').val().replace(/[\t ]+/g,' '));
});
I already solved the extra spaces part my only problem is the "enter" part.
Upvotes: 0
Views: 3347
Reputation: 66693
Use \s+
instead to match all whitespace characters including spaces, tabs, newlines etc.
$('#q').val($('#q').val().replace(/\s+/g,' '));
Demo: http://jsfiddle.net/eSE9Y/1/
\s stands for "whitespace character". (...) which characters this actually includes, depends on the regex flavor. (...) \s matches a space, a tab, a line break, or a form feed. Most flavors also include the vertical tab (...). In flavors that support Unicode, \s normally includes all characters from the Unicode "separator" category. Java and PCRE are exceptions once again. But JavaScript does match all Unicode whitespace with \s.
Reference: http://www.regular-expressions.info/shorthand.html
Upvotes: 1
Reputation: 239643
Newline character can be represented with \n
in the RegEx. So, just change your RegEx like this
/[\t\n ]+/g
Instead, you can simply replace all whitespace characters with a single space, with this regular expression
/\s+/g
Quoting from MDN RegularExpressions page, about \s
Matches a single white space character, including space, tab, form feed, line feed. Equivalent to [ \f\n\r\t\v\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000].
Upvotes: 1