Reputation: 131
Ho to allow upto three blank spaces in a string using java script regular expression
I tried with the following
<script type="text/javascript">
var mainStr = "Hello World";
var pattern= /^(?=[^ ]* ?[^ ]*(?: [^ ]*)?$)(?=[^-]*-?[^-]*$)(?=[^']*'?[^']*$)[a-zA-Z '-]*$/;
if(pattern.test(mainStr)){
alert("matched");
}else{
alert("not matched");
}
</script>
Upvotes: 1
Views: 441
Reputation: 25874
The following regex matches 0-3 whitespace characters.
\s{0,3}
The following regex matches strings with up to 3 whitespace characters.
^[^\s]+\s?[^\s]*\s?[^\s]*\s?[^\s]*$
Examples:
"ab" - (match)
"a b" - (match)
"a b c" - (match)
"a b c d" - (match)
"a b c d e" - (doesn't match)
"a b c d e f" - (doesn't match)
(Still waiting for examples from the questioner!)
Upvotes: 1
Reputation: 66217
If the sole purpose of what you want to do is to permit up to 3 spaces anywhere in a string - why not simply compare the length of the string before and after removing all spaces (or whiespace characters \s
if relevant)? If the difference is more than 3 characters - it contains more than 3 spaces.
e.g.
var mainStr = "Hello Wor l d";
if(mainStr.replace(/ /g, '').length > (mainStr.length - 3)) {
alert("matched");
}else{
alert("not matched");
}
If your requirement is more specific - you need to clarify (edit the question), otherwise don't use regular expressions when they aren't necessary.
Upvotes: 1