0

I have a regex that matches all the links in an html code, but I'd like to match only those links that have a certain pattern in either its text or in any of its attributes. In fact, I want to match only those links that have the pattern ${whatever_text}.

I'll give you an example to clarify things:

var text = '<a href="/foo">foo</a> some sample text <a href="${bar}">bar</a>';
var pattern = /<a (.+?)<\/a>/igm;
var matches = text.match(pattern);
document.write(matches);

The previous regex matches the two links in the text, but I need to build a regex that matches only the last link. I've tried with the following regex /<a (.*?\$\{.+?\}.*?)<\/a>/igm but it matches everything in between the opening tag of the first link and the closing tag of the second link.

var text = '<a href="/foo">foo</a> some sample text <a href="${bar}">bar</a>';
var pattern = /<a (.*?\$\{.+?\}.*?)<\/a>/igm;
var matches = text.match(pattern);
document.write(matches);

Thanks beforehand!

beni0888
  • 1,050
  • 1
  • 12
  • 40
  • don't use regex for this. Use the DOM. – zzzzBov May 27 '16 at 15:39
  • I think I can't use the DOM for this because the html code is in a WYSIWYG editor in a form field. In addition, I can't see an easy way of doing this using the DOM. It would be nice if you could give me some clues or examples ;) – beni0888 May 27 '16 at 15:42
  • @beni0888, throw the contents in a [document fragment](https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment) and use the DOM apis. – zzzzBov May 27 '16 at 15:48
  • @zzzzBov I think that what you propose its not a proper solution for this problem. I can't see an easy way of performing what I need with DOM API and DOM selectors. In addition, it doesn't matter if the stuff in the text are html elements, I'm asking about regex related problems, not about HTML and DOM. – beni0888 May 27 '16 at 16:01
  • "I can't see an easy way of performing what I need" just because you don't know how to use a tool doesn't make it the wrong tool. [Regex is very much the wrong tool for this job](http://stackoverflow.com/q/1732348/497418), which involves finding nodes and reading attributes or text content. I can only point you in the right direction, so if you think you know better: good luck, *you're going to need it*. – zzzzBov May 27 '16 at 16:13

1 Answers1

1

You can use this negative lookahead regex:

/<a (?:(?!<a[^>]*>).)*?\$\{[^}]+\}.*?<\/a>/

RegEx Demo

(?:(?!<a[^>]*>).)*? is negative lookahead to ensure we don't match another <a..> once we are paste the <a in matching.

anubhava
  • 761,203
  • 64
  • 569
  • 643