user2962526
user2962526

Reputation: 131

how to allow upto 3 spaces in a string using javascript regular expression

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

Answers (2)

Nick Grealy
Nick Grealy

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

AD7six
AD7six

Reputation: 66217

Do you need a regex at all

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

Related Questions