I am trying to write a regex expression in javascript to validate whether a string is a valid jquery selector. This is strictly educational and not a particular requirement in any project of mine
Pattern
/^(\$|Jquery)\(('|")[\.|#]?[a-zA-Z][a-zA-Z0-9!]*('|")\)$/gi
It works fine for below tests
$("#id")//true
$('.class')//true
jquery('.class')//true
jquery('div')//true
My problem is that the test on $('#id") also returns true i.e, using mixing single and double quote in js in invalid. How to restrict this. Can we have conditional regex?
const pattern = /^(\$|Jquery)\(('|")[\.|#]?[a-zA-Z][a-zA-Z0-9!]*('|")\)$/gi;
[
`$("#id")`, //true
`$('.class')`, //true
`jquery('.class')`, //true
`jquery('div')`, //true
].forEach(str => console.log(pattern.test(str)));
You can capture the first quote or doublequote in a group, and require that same group (the same quote or doublequote) at the end, using a backreference:
const re = /^(?:\$|Jquery)\((['"])[\.#]?[a-zA-Z][a-zA-Z0-9!]*\1\)$/gi;
console.log(re.test(`$("#id")`))
console.log(re.test(`$('#id")`))
console.log(re.test(`$("#id')`))
console.log(re.test(`$('#id')`))
There are also a couple other things to fix:
/^\$|Jquery...
meant that any string starting with $ would fulfill the regex. Enclose it in a group instead.
Single quote ' doesn't need escaping - best to remove the backslash.
Rather than
[\.|#]?
if you want to possibly match . or # (and not a pipe), use [\.#]? instead
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With