Ray Lawlor Ray Lawlor - 1 year ago 67
AngularJS Question

Modifying "a" tags in a string and return the updated string in javascript function

I'm getting string data via a CMS that contains a few anchor links.

I'm going to compiling the code into an app (via Ionic Framework) so I need the "a" tags to contain an onClick function that will use the "inappbrowser" Cordova plugin.

So I've set up a function called "processLinks" to send the string to be processed:

<p ng-bind-html="processLinks(data[0].value)"></p>

And the function is this:

$scope.processLinks = function (inputText) {
return inputText.replace(/<a.*href="(.*?)".*>(.*?)<\/a>/gi, "");

Currently, this simply removes the links (Which was a temporary solution).

So I need help achieving the following:

I need to send the string into the function, then modify the links by inserting the onClick function with the "href" from each link:

I need to modify:

<a href="http://www.thesite.com"></a>

to become:

<a href="http://www.thesite.com" onclick="window.open('http://www.thesite.com', '_system', 'location=yes'); return false;"></a>

Then return the processed string.

Answer Source

Try this new regular expression:

$scope.processLinks = function (inputText) {
    return inputText.replace(/(<a.*href="(.*?)".*)(>.*?<\/a>)/gi, '$1 onClick="window.open(\'$2\', \'_system\', \'location=yes\'); return false;"$3');

A bit explanation: We capture 3 groups from the in put text:

  1. The first part of the link, right before the first > that closing <a
  2. The link
  3. The second part of the link, start with > until the end of the link.

Then we assemble the result by joining 3 above groups with the onClick....

At least it works for your example ;-)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download