Reputation: 11334
I'm a bit confused as to how to solve this problem. Seems standard and commonly occurring but couldn't find anything worthwhile. I have an HTML textarea and a textbox for input. I want to validate the following:
Intuitively if I can just get solution to #3 to work I guess it could automatically feed it into a char counter function and it would be valid, correct?
Any ideas how to go about doing this? jQuery or javascript are both acceptable :)
Upvotes: 1
Views: 383
Reputation: 1074038
You can replace all occurrences of more than one space with one space via a regular expression (live example):
var text = "a b c";
text = text.replace(/ +/g, ' ');
alert(text); // "a b c"
That works by looking for a space followed by one or more spaces, globally, and replacing them with just the one space.
Note that that regular expression is specific to spaces. It doesn't handle other forms of whitespace. If you wanted to replace all occurrences of two or more whitespace characters with one space, you could do this:
var text = "a \t\r\n b \t\r\n c";
text = text.replace(/\s\s+/g, ' ');
alert(text); // "a b c"
That uses the \s
(whitespace) character class. Note that most implementations do a pretty good job applying \s
correctly, but there are bugs with some of them related to some of the more esoteric whitespace characters defined by Unicode even though the specification clearly says they should also be handled. (You can find out how your favorite browsers do here, or read up more on the issue here.) It's very unlikely you'd care for the use case you describe, you probably don't have to worry about it.
Upvotes: 2