Probably I am not able to achieve this because I don't know much about regEx.
I have an array of unique links uniqueLinks.
Whenever those links appear in the HTML code I have my textarea, I want them to be replaced with {{tracking_link_N}} where N stands for the key. Right now I have the following function called when a button is pressed
function detect_links() {
var links = [];
var uniqueLinks = [];
var html = $("textarea[name=html]").val();
// Getting all the links in the textarea to replace them
$(html).find('a').each(function() {
links.push($(this).attr('href'));
})
// Creating an array of unique links uniqueLinks
$.each(links, function(i, el) {
if ($.inArray(el, uniqueLinks) === -1) uniqueLinks.push(el);
});
$.each(uniqueLinks, function(key, value) {
var newHTML = $("textarea[name=html]").val().replace(value, '{{tracking_link' + key + '}}');
$("textarea[name=html]").val(newHTML);
});
}
My textarea is:
<textarea name="html" class="form-control" rows="15"></textarea>
With this code so far it only replaces the first occurrence of the URL in the textarea. In some cases however the same URL appears multiple times in the textarea. E.g.
<a href="http://google.co.uk">Google</a>
<a href="http://google.com">Google 2</a>
<a href="http://google.co.uk">Google 3</a>
My code returns
<a href="http://google.co.uk">{{tracking_link0}}</a>
<a href="http://google.com">{{tracking_link1}}</a>
<a href="http://google.co.uk">Google 3</a>
It should return instead
<a href="http://google.co.uk">{{tracking_link0}}</a>
<a href="http://google.com">{{tracking_link1}}</a>
<a href="http://google.co.uk">{{tracking_link0}}</a>
What I tried reading the other discussions is to change the replace()
function like this
replace(/value/g, '{{tracking_link' + key + '}}');
But I don't get any appreciable result.
My URLs contain parameters as well, for example:
http://tracking.testapp.com/affil?offer=105&id=1152
Thanks for any help to address this issue.
PS: explaining the downvotes you give to questions makes them more believable