user1775888 user1775888 - 1 month ago 9
Javascript Question

How to use specific website in regex

I want the regex pattern to only match

a9.com
or
www.a9.com


I have tried add
?
before www.
/?([www]+\.)+[\ba9\.com\b]/;
but it shows error..

Did I miss anything ?

hope this result

a9.com true
www.a9.com true
a91.com false
www.a91.com false


https://jsfiddle.net/c2wsds0g/

var str = 'a9.com';

var regexPattern = /([www]+\.)+[\ba9\.com\b]/;
var result = regexPattern.test(str);
console.log(result)


only regex. not use split or other method

Answer

This Regex sould do the trick:

(www\.)?a9\.com

The ´?´ quantifier, to make the group optional goes after the group, not before.

Bonus: I always test my regex with regexpal.com, you should try it. You´ll find a handy cheat sheet there too.

Comments