0

I have a long string which basically contains the whole HTML code of a page.

There are links in this page and I need to add a set of parameters at the end of these links.

Nb : All href are the same in the all page.

I managed to extract the URL in a variable with this code (html var contains my html code) :

var href = html.match(/href="([^"]*)/)[1];

Adding extra parameters :

var newHref = href+'&n=$ln$&p=$fn$&e=$e$';

I escape the first href with this function for regexp purpose :

function escapeRegExp(str) {
    return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|\=\%\:\&]/g,"\\$&");
}

Then I try to perform the replacement in the code :

var reCompletion = new RegExp(escapeRegExp(href),"g");
html.replace(reCompletion, newHref);

When I run this code it cannot find any match with the URL and perform no replacement at all.

Here is the kind of URL I have to complete :

http://action.mySite.com/trk.php?mclic=P4CAB9542D7F151&urlrv=http%3A%2F%2Fjeu-centerparcs.com%2F%23%21%2F%3Fidfrom%3D8&urlv=517b975385e89dfb8b9689e6c2b4b93d

Once escaped :

http\:\/\/action\.mySite\.com\/trk\.php\?mclic\=P4CAB9542D7F151\&urlrv\=http\%3A\%2F\%2Fjeu\-centerparcs\.com\%2F\%23\%21\%2F\%3Fidfrom\%3D8\&urlv\=517b975385e89dfb8b9689e6c2b4b93d

Does anyone have any clue about this ?

Arnaud
  • 141
  • 2
  • 9

1 Answers1

1

The problem is in $ symbols in the replacement part: the dollars must be doubled to be replaced with 1 $:

var newHref = (href+'&n=$ln$&p=$fn$&e=$e$').replace(/\$/g, '$$$$');

Also, remove unnecessary escaping symbols from escapeRegExp:

function escapeRegExp(str) {
    return str.replace(/[-[\]\/{}()*+?.\\^$|=%:&]/g,"\\$&");
}

Here is a snippet:

var html = "More here http://action.mySite.com/trk.php?mclic=P4CAB9542D7F151&urlrv=http%3A%2F%2Fjeu-centerparcs.com%2F%23%21%2F%3Fidfrom%3D8&urlv=517b975385e89dfb8b9689e6c2b4b93d text<br/>And more here http://action.mySite.com/trk.php?mclic=P4CAB9542D7F151&urlrv=http%3A%2F%2Fjeu-centerparcs.com%2F%23%21%2F%3Fidfrom%3D8&urlv=517b975385e89dfb8b9689e6c2b4b93d";
var href = "http://action.mySite.com/trk.php?mclic=P4CAB9542D7F151&urlrv=http%3A%2F%2Fjeu-centerparcs.com%2F%23%21%2F%3Fidfrom%3D8&urlv=517b975385e89dfb8b9689e6c2b4b93d";
var newHref = (href+'&n=$ln$&p=$fn$&e=$e$').replace(/\$/g, '$$$$');
function escapeRegExp(str) {
    return str.replace(/[-[\]\/{}()*+?.\\^$|=%:&]/g,"\\$&");
}
var reCompletion = new RegExp(escapeRegExp(href),"g");
html = html.replace(reCompletion, newHref);
document.body.innerHTML = html;
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563