简体   繁体   中英

validation of javascript regular expression

I have the following string of javascript:

#d1{width:100px;} it looks like css code

now I wrote a regular expression that finds of an element starting with # or . in the string.

the regular expression is like this:

/(?:(#|\.)([A-Za-z0-1\-]+))/g

and the above regular expression matches successfully such strings like the above one.

but now when I tested this regular expression on the above string in Google console with then it returns false

the which I wrote was:

var str = "#d1{width:100px} " // returns undefined
var regex = / (?:(#|\.)([A-Za-z0-1\-]+)) /g //undefrined
regex.test(str) // returns false

Why it is not working?

You have spaces in your regular expression which you propably don't want there:

var str = "#d1{width:100px} " // returns undefined
var regex = /(?:(#|\.)([A-Za-z0-1\-]+))/g //undefrined
//           ^-------------------------^----- see, no spaces here
regex.test(str) // returns true

Try this. These spaces between / and parantheses are jerks.

 function regtest() { var str = "#d1{width:100px}" // returns undefined var regex = /(?:(#|\\.)([A-Za-z0-1\\-]+))/g //undefrined alert(regex.test(str)); } 
 <button onclick="regtest()">Test</button> 

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