Regex, if the variable contains a particular Character

Asked

Viewed 27 times

0

I have a link for exexplo:

<a href="#sessao">Sessão</a>

And another link :

<a href="https://...">Link Externo</a>

I would like to know how, I believe by regular expression, a way for me to test if my link contains the "#", so I can provide a!

1 answer

4

You don’t need regex, just use the indexOf.

For example:

var href = elemento.getAttribute('href');
if (href.indexOf('#') != 0) e.preventDefault();

The String.indexOf(char) gives you the position of a given character in a string. If it is there the position should be 0, if it is not a "normal link".

Just to answer your question with regex, which I advise against in this case, it could be so:

var href = elemento.getAttribute('href');
if (!href.match(/^#/)) e.preventDefault();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.