KayKay
KayKay

Reputation: 401

Regex filter does not do an exact match

I am using the the following regex to filter

 return this.href.match(/goto.com|xyz.com|loop.com/g);

However if there's a url called dogoto.com, that too gets filtered. How can I change my Regex to disallow that?

http://jsfiddle.net/wQYuz/7/

Upvotes: 1

Views: 80

Answers (3)

Bill Criswell
Bill Criswell

Reputation: 32941

You can add \b (a word boundary) on both sides of it.

return this.href.match(/\b(goto\.com|xyz\.com|loop\.com)\b/g);

Here's a quick demo: http://jsfiddle.net/wQYuz/9/

Upvotes: 2

PurkkaKoodari
PurkkaKoodari

Reputation: 6809

^ matches the start of the string. You could do that:

return this.href.match(/^(goto\.com|xyz\.com|loop\.com)/g);

Or, you could match any non-alphanumeric character there:

return this.href.match(/\Wgoto\.com|\Wxyz\.com|\Wloop\.com/g);

Also, you might want to escape your dots (done here) because otherwise the dot matches any character, not just itself.

Upvotes: 1

OGHaza
OGHaza

Reputation: 4795

Try:

/\b(goto\.com|xyz\.com|loop\.com)\b/g

\b matches at the start/end of a word. It needs brackets around the words otherwise doxyz.com and doloop.com would still match.

Fiddle

Upvotes: 0

Related Questions