-1

I have a scenario where I need to inject some style attributes into a href.

Example. I need to turn this:

<a href="https://google.com">Google</a>

Into this:

<a href="https://google.com" style="color:blue">Google</a>

I need to select the area between the closing quote of the link, and the closing bracket of the <a> In the above example it's: style="color:blue" or before the attribute is inserted, simply that position in the string.

From my searching around and playing in regex101 I can select everything up until the closing quote with something like this:

a\s+(?:[^>]*?\s+)?href=(["'])(.*?)\1

but I need the inverse of that, I need to select everything from the quote until the closing bracket > before Google</a> to inject the attributes.

Unfortunately regex is something I only get to play with infrequently so hoping someone could give me a hand. Thanks.

Vee
  • 9
  • Possible duplicate of [RegEx match open tags except XHTML self-contained tags](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – Daniel May 24 '18 at 11:39
  • have you considered using javascript to add the style to the link? – Lelio Faieta May 24 '18 at 11:40
  • @LelioFaieta thanks for the suggestion. Unfortunately I'm pretty limited in my options and I'm working with html interpreted fields inside another system which limits my possibilities. I've found the above to be the only thing that works. – Vee May 25 '18 at 01:04

1 Answers1

1

Why not use css? Stick this in your <head> section:

<style>
    a {color:blue;}
</style>

Or if you must use regex, you'll need to search for (<a href="[^"]*")> and replace it with \1 style="color:blue;"> (or for some regex engines, you need to use $1 instead of \1).

See example here, on regexr.com

enter image description here

Richard Inglis
  • 5,888
  • 2
  • 33
  • 37
  • Thank you for your input! Unfortunately I do need to use regex. I'm working with HTML interpreted fields within another system which itself does a lot of styling and unfortunately it messes up link colors. The only way I've found to get around this is through the above. I've plugged the regex sample you gave into regex101 but it doesn't seem to match on anything. Any idea what I'm doing wrong? – Vee May 25 '18 at 01:00
  • Updated my answer: regex101 doesn't let you do *replace* - try regexr.com – Richard Inglis May 25 '18 at 02:18