Tom Pinchen
Tom Pinchen

Reputation: 2497

JS Regex to check that string only includes anchor

I am trying to create a regex that will return true only when the string only contains an anchor like so <a href="www.something.com">Link</a>.

Currently I have the following regex which almost works (?=.*^<a)(?=.*<\/a>).*/g

This works for the following scenarios:

<a href="www.something.com">Link</a> - Matches successfully

words before <a href="www.something.com">Link</a> - No matches - success

<a href="www.something.com">Link</a> words after - finds match - Not successful :(

I think I'm pretty close, I just need to know how to not find a match if there are any characters after the </a>.

Upvotes: 0

Views: 158

Answers (1)

eMontielG
eMontielG

Reputation: 416

Add a $ after the last >

(?=.*^<a)(?=.*<\/a>$).*

regex101

Alternatively, this regex matches links and discards everything else, irregardless of whether there are one or more links in the same line.

<a.*?\/a>

Upvotes: 1

Related Questions