jquery - Checking for bunch of whitespaces in javascript to prevent blank data being sent and trimming the intermediate spaces -
i'm bit confused how solve problem. seems standard , commonly occurring couldn't find worthwhile. have html textarea , textbox input. want validate following:
- the user shouldn't allowed enter bunch of white spaces in textarea - if 15 characters minimum 16 whitespace characters shouldn't count towards valid data. simple char count won't detect this.
- one can enter 16 whitespaces , 1 letter, still invalid data! anyway check check validity here (it should counted 2 characters per below point)?
- trimming unnecessary whitespaces - i.e., if enters character/word , follows 10 whitespaces , character , set of whitespaces, i'd them trimmed single white space. happens when enter answer/new question on so. if enter bunch of whitespaces automatically trim it. tried searching around nothing whitespace specific.
intuitively if can solution #3 work guess automatically feed char counter function , valid, correct?
any ideas how go doing this? jquery or javascript both acceptable :)
you can replace occurrences of more 1 space 1 space via regular expression (live example):
var text = "a b c"; text = text.replace(/ +/g, ' '); alert(text); // "a b c"
that works looking space followed 1 or more spaces, globally, , replacing them 1 space.
note that regular expression specific spaces. doesn't handle other forms of whitespace. if wanted replace occurrences of 2 or more whitespace characters 1 space, 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 \s
(whitespace) character class. note implementations pretty job applying \s
correctly, there bugs of them related of more esoteric whitespace characters defined unicode though specification says should handled. (you can find out how favorite browsers here, or read more on issue here.) it's very unlikely you'd care use case describe, don't have worry it.
Comments
Post a Comment