简体   繁体   中英

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>

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!)

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.

eg

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM