...">

HTML Anchor replaces RegEx

I have HTML data that I will use in a client application. I need Regex. Replace tags <a>from

<a href="Bahai.aspx">Bahai</a>

to

<a href="#" onclick="process('Bahai.aspx');return false;">Bahai</a>

In C # using RegExReplace with a regex similar to

<a[^>]*? href=\"(?<url>[^\"]+)\"[^>]*?>(?<text>.*?)</a>

Ideas?

+3
source share
3 answers

In C # you can use this code:

Regex.Replace("<a href=\"Bahai.aspx\">Bahai</a>", 
            "<a href=\"(.+?)\">(.+?)</a>", "<a href=\"#\" onclick=\"process('$1');return false;>$2</a>",
            RegexOptions.IgnoreCase);

It will return a string that matches what you need.

+3
source

In general, it is best not to parse HTML with regular expressions. Instead, try the Html Agility Pack .

+1
source

javascript, Bahai.aspx, , javascript, . javascript , , jquery?

Let's say you tag anchor tags class="doProcess", after which you can use the following jQuery script to change the links:

$(document).ready(function(){
  $('a.doProcess').each(function(){
    var a = $(this);
    var href = a.attr('href');
    a.attr('href','#');
    a.click(function(){
      process(href);
      return false;
    });
  });
});

then users with and without javascript will be sent to Bahai (if this is what your process method does) :)

0
source

Source: https://habr.com/ru/post/1722866/


All Articles