简体   繁体   中英

Javascript Regex Matching Everything

I have this bit of Javascript,

if (/[A-Za-z0-9-]+/.test(sZip)) {
   alert(Match!);
}

and I'm using this as my test case "1234;"

I don't want "1234;" to be a match, I want only for example "1234" or "12 34" or "12-34" to match.

/[A-Za-z0-9-]+$/

($是关键:它表示字符串结束,不再是字符)

Start the regular expression with ^ and end it with $ . This way you tell it to match the whole string against the pattern. MDN docs .

If you want the space matched, you need to include it in the brackets. For space and dash to delimit alphanum fields, take this approach:

/^([A-Za-z0-9]+[ -])*[A-Za-z0-9]+$/
---^ 0 or more "ABC123-" fields
---------------^ separated by either dash or space
---------------------^ but at least once a "ABC123" field (no dash)
    if (/[A-Za-z0-9-]+$/.test(sZip)) { 
      alert(Match!); 
    }  

This should work:

if (/[A-Za-z0-9-]+\s/.test(sZip)) {
   alert(Match!);
}

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