0

I have a paragraph of text in a javascript variable which contains multiple anchor, area and link tags. I would like to replace all of the href links other then the link tags with some other link. For example my current regex matching all the href not containing (mailto:) and (abc-url)

var r_domain = 'testlink.com';
var s = 'someencryptedstring';

var pattern = /href[\s]*=[\s]*('|")(?!mailto:)(?!#)((?:(?!\abc-url\b)[^('|")])*)('|")/ig;

var replace_pattern = 'href=\"http://'+r_domain+'/link.php?str='+s+'&mailin-url=$2"';

var body = '<a href="http://example.com" >abc</a> test data <a href="http://test.com/test.php?str=someencryptedstring&abc-url=http://cdf.com" > link </a> test last <link rel="stylesheet" href="http://csslink.com/forms.css" type="text/css" media="screen, projection" />  area test <a href="http://example_1.com" > xyz </a>';

var re      = new RegExp(pattern);
var replaced  = body.replace(re , replace_pattern);
console.log(replaced);

It should replace the below links only:

href="http://example.com"
href="http://example_1.com"

It should not replace the below links:

href="http://test.com/test.php?str=someencryptedstring&abc-url=http://cdf.com"
href="http://csslink.com/forms.css"

The output should be as below (console.log(replaced);):

<a href="http://testlink.com/link.php?str=someencryptedstring&mailin-url=http://example.com" >abc</a> test data <a href="http://test.com/test.php?str=someencryptedstring&abc-url=http://cdf.com" > link </a> test last <link rel="stylesheet" href="http://csslink.com/forms.css" type="text/css" media="screen, projection" />  area test <a href="http://testlink.com/link.php?str=someencryptedstring&mailin-url=http://example_1.com" > xyz </a>

1 Answer 1

0

I have changed the regex for the pattern and replace_pattern and kept the other script as it is. It is working fine for me.

The new regex for the pattern and replace_pattern are as below:

var pattern = /(<(a|area) [^>]*)href[\s]*=[\s]*('|")(?!mailto:)(?!#)((?:(?!\abc-url\b)[^('|")])*)('|")/ig;

var replace_pattern = '$1href=\"http://'+r_domain+'/link.php?str='+s+'&mailin-url=$4"';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.