Regex, if the variable contains a certain character

0

I have a link by 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 to test if my link contains "#", so I can give a preventDefault whatsoever!

    
asked by anonymous 15.07.2016 / 22:48

1 answer

4

You do not need regex, just use indexOf .

For example:

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

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

Just to answer your question with regex, which I advise against in this case, might look like this:

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