0

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?

1
  • have you tried it without the spaces? regex = /(?:(#|\.)([A-Za-z0-1\-]+))/g? Commented Dec 5, 2014 at 9:23

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

1 Comment

you don't need to go for capturing or non-capturing groups. Just [#.][A-Za-z0-1-]+ would be fine.
1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.