My problem is the following:
I have a page with many links
Some of them have a specific pattern :
http://www.example.com/.../?parameter1=...¶meter2=PARAMETER2
What i want to do is to change these links' href to the value of the parameter2 using JavaScript.
For example if i have a link like :
text here
what i want to do after the script runs is to have a link like this:
text here
Any suggestion would be truly appreciated!!!
Thank you all in advance!!!
If you are using jquery
then use the following code
$(function() {
$("a[href^='www.example.com']").each(function(){
var ele = $(this);
var href = ele.attr("href");console.log(href);
var index = href.lastIndexOf("parameter2");
var param_2 = href.substring((index + 11));
ele.attr("href", param_2);
});
});
http://jsfiddle.net/LVNeC/
function getUrlVars(_url)
{
var vars = [], hash;
var hashes = _url.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var myLINK = document.getElementById("mylink");
var url = myLINK.href;
myLINK.href = getUrlVars(url )["parameter2"];
Related
We do have some Campaigns (Google, facebook,...) When the user arrives the landingpage (abo.mysite.com) he does have the utm parameter utm_source=theCampaignSource. When the user clicks an CTA the CTA gives an new UTM utm_source=abo and he goes to shop.mysite.com.
We are not able to remove the UTM from abo.mysite.com.
Is there a way to check if a user have already an UTM, and when he does have one to kepp them until shop.mysite.com? So we know that the user is comming from Google (...)?
We know that how this Thing is set up is a very bad practice, and we are working on it.
Ive found a code snippet which is manipulating the links on a site:
links.forEach(function(link){
link.setAttribute("href","abo.mysite.com")
})
but i couldn get it work - cause i do have a lack of experience.
Update
To my specific needs a made it that way:
1) Remove existing UTM from Links on the Site
<script>
var link = document.getElementsByTagName("a");
for (var i = 0; i < link.length; i++) {
link[i].href = link[i].href.replace(/(\?)utm[^&]*(?:&utm[^&]*)*&(?=(?!utm[^\s&=]*=)[^\s&=]+=)|\?utm[^&]*(?:&utm[^&]*)*$|&utm[^&]*/gi, '$1');
}
</script>
2) Hash the UTM in the URL
<script>
if(!window.jQuery) {
document.write('<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js">\x3C/script>');
}
</script>
<script type="text/javascript">
$(document).ready(function() {
function getUrlVars() {
var vars = [],
hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var parameters = getUrlVars();
var utm_source = decodeURIComponent(parameters['utm_source']);
var utm_campaign = decodeURIComponent(parameters['utm_campaign']);
var utm_medium = decodeURIComponent(parameters['utm_medium']);
</script>
3)rewrite every URL on the Site with the hashed UTMs
<script>
$('a').each(function(){
$(this).attr('href', $(this).attr('href') + '?utm_source=' + utm_source + '&utm_campaign' + utm_campaign + '&utm_medium' + utm_medium);
});
});
Edit
Thanks to Michele Pisani
this works well - BUT, if a user does not have an UTM, and he clicks the button, the UTM will be set to undefined
Is there a way to set the UTM Parameter from the URL when the User already has one, or to use the existing UTM (which are hardcoded in the button) when he does not have an UTM in the URL.
Edit 2 & update
Finally - with the help of you guys - i found a solution:
<script>
var link = document.querySelectorAll('a:not([href*="#"])');
for (var i = 0; i < link.length; i++) {
//link[i].href = link[i].href.replace(/(\?)utm[^&]*(?:&utm[^&]*)*&(?=(?!utm[^\s&=]*=)[^\s&=]+=)|\?utm[^&]*(?:&utm[^&]*)*$|&utm[^&]*/gi, '$1');
}
</script>
<script type="text/javascript">
$(document).ready(function() {
function getUrlVars() {
var vars = [],
hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
//var parameters = getUrlVars();
//var utm_source = decodeURIComponent(parameters['utm_source']);
//var utm_campaign = decodeURIComponent(parameters['utm_campaign']);
//var utm_medium = decodeURIComponent(parameters['utm_medium']);
var url_string = window.location.href; //window.location.href
var url = new URL(url_string);
//var c = url.searchParams.get("c");
var utm_source = url.searchParams.get("utm_source");
var utm_campaign = url.searchParams.get("utm_campaign");
var utm_medium = url.searchParams.get("utm_medium");
$('a:not([href^="#"])').each(function() {
if(utm_source != "" && utm_source != null){
var href = $(this).attr("href");
href = href.replace(/(\?)utm[^&]*(?:&utm[^&]*)*&(?=(?!utm[^\s&=]*=)[^\s&=]+=)|\?utm[^&]*(?:&utm[^&]*)*$|&utm[^&]*/gi, '$1');
$(this).attr("href",href);
$(this).attr('href', $(this).attr('href') + '?utm_source=' + utm_source + '&utm_campaign=' + utm_campaign + '&utm_medium=' + utm_medium);
}
});
});
</script>
With JavaScript, to remove UTM parameters from links in page you can try this function with regex:
var link = document.getElementsByTagName("a");
for (var i = 0; i < link.length; i++) {
link[i].href = link[i].href.replace(/(\?)utm[^&]*(?:&utm[^&]*)*&(?=(?!utm[^\s&=]*=)[^\s&=]+=)|\?utm[^&]*(?:&utm[^&]*)*$|&utm[^&]*/gi, '$1');
}
If you are using Google Tag Manager you can add it in a custom HTML tag and fires it on DOM Ready.
If you want to keep the fragment in the URL you can modify the function in this way:
var link = document.getElementsByTagName("a");
for (var i = 0; i < link.length; i++) {
arr_link = (link[i].href).split("#");
var fragment = "";
if (arr_link[1]) { fragment = "#" + arr_link[1]; }
var my_new_url = arr_link[0].replace(/(\?)utm[^&]*(?:&utm[^&]*)*&(?=(?!utm[^\s&=]*=)[^\s&=]+=)|\?utm[^&]*(?:&utm[^&]*)*$|&utm[^&]*/gi, '$1');
link[i].href = my_new_url + fragment;
}
const ourUTMs = new URL(location.href).searchParams;
document.body.onclick = (e) => {
if (!isParamsContainsUTM(ourUTMs) || e.target.tagName !== "A") {
return;
}
try {
// Is valid url?, else we go to catch =)
const url = new URL(e.target.href);
e.preventDefault();
// Remove all utm params from link;
Array.from(url.searchParams).forEach(([k]) => {
if (k.startsWith("utm_")) {
url.searchParams.delete(k);
}
});
// Add our utm_ params to link
Array.from(ourUTMs).forEach(([k, v]) => {
url.searchParams.append(k, v);
});
// Open URL
window.open(url.toString());
} catch (e) {}
};
const isParamsContainsUTM = (arr = new URLSearchParams()) =>
Array.from(arr).some(([key]) => key.startsWith("utm_"));
I have this url:
http://test.words.aspx#word_id=1034374#lang_code=en
I need to get the values of word_id and Language code and assign them to variables.
var word_id = 1034374;
var lang_kod = en;
Here is the code you need:
var link = window.location;
var data = link.split("#");
var word_id = data[1].split("=")[1];
var lang_code = data[2].split("=")[1];
With window.location you get the url that you currently are (an alternative is document.location.
Then you split it by the hash symbol (link.split("#")) and the result is stored as an array of strings (data) which now contains http://test.words.aspx at index 0, word_id=1034374 at index 1 and lang_code=en at index 2;
What you have to do now is split the string at index 1 by the equals symbol (data[1].split("=")). This also is an array of string which has the word_id at index 0 and 1034374 at index 1 which is what you need (data[1].split("=")[1]).
Following the same logic you also get the lang_code variable.
Test it here:
var link = "http://test.words.aspx#word_id=1034374#lang_code=en"
var data = link.split("#");
var word_id = data[1].split("=")[1];
var lang_code = data[2].split("=")[1];
console.log("Word ID = " + word_id);
console.log("Lang Code = " + lang_code);
Hope this was helpful :)
You should really only have one URL fragment. But in your case you could do the following to achieve this.
var url = "http://test.words.aspx#word_id=1034374#lang_code=en"; // or use window.location;
var url_splitted = url.split('#');
alert((url_splitted[1]).split('=')[1]); // showing you the values
alert((url_splitted[2]).split('=')[1]); // showing you the values
var work_id = (url_splitted[1]).split('=')[1];
var lang_code = (url_splitted[2]).split('=')[1];
Working JSFiddle: https://jsfiddle.net/o0nwyvfz/
Note:
If you are about to use multiple URL fragments, I'd suggest you to use URL parameters e.g.: http://test.words.aspx?word_id=1034374&lang_code=en
Which you could retrieve by:
A solution provided by: http://www.jquerybyexample.net/2012/06/get-url-parameters-using-jquery.html
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
And this is how you can use this function assuming the URL is,
http://test.words.aspx?word_id=1034374&lang_code=en
var tech = getUrlParameter('word_id');
var blog = getUrlParameter('lang_code');
I am building a page that needs to be able to get a all the file links on a webpage and add them to a dropdown list. Original it was the script was supposed to be on the same page as the files but now it needs to search an external. This is what I used before the change
<script>
$(document).ready(function() {
var arr = [];
var filenames = [];
var alt_var;
var baseURL = "www.fakeurl.com"
$('.ms-vb-icon').find('a').each(function(){
var temp = $(this).attr('href')
$(this).find('img').each(function(){
alt_var = $(this).attr('alt');
});
if(temp.indexOf('.csv') != -1){arr.push(temp); filenames.push(alt_var);}
});
for(i = 0; i < arr.length; ++i)
{
var x = document.createElement('li');
var a = document.createElement('a');
var t = document.createTextNode(" " + filenames[i]);
var fullURL = baseURL + arr[i];
a.setAttribute('href',"#");
a.setAttribute('class', "glyphicon glyphicon-file");
a.setAttribute('id', baseURL + arr[i]);
a.setAttribute('onclick', "drawChart(this.id)");
a.appendChild(t);
x.appendChild(a);
document.getElementById("dropdownfiles").appendChild(x);
}
});
</script>
How can I change this to search an external url. (PS new to Javascript)
Not sure if this is the cleanest way but you could add a hidden iframe on the page and then search in there.
css:
.externalSearcher iframe {
display: none;
}
html:
<div class="externalSearcher"></div>
js:
$('.externalSearcher').append('<iframe src="' + externalLink + '"></iframe>');
$('.externalSearcher').find('a').each(function () {
//do what you want with the link
});
I am trying to direct after user click on "Finish" on a sharepoint survey. But the following code executes when user click on "Respond to this survey". Any idea what is happening.
<script type="text/javascript">
function redirect()
{
var inputcCtrls = document.getElementsByTagName("input");
for(var m=0; m<inputcCtrls.length; m++)
if(inputcCtrls[m].type=='button'&&inputcCtrls[m].value=='Finish')
var funcOnClick = inputcCtrls[m].onclick;
inputcCtrls[m].onclick = window.location = "http://www.google.com/";
}
redirect();
</script>
I don't know about javascript, but in c# the code block
var funcOnClick = inputcCtrls[m].onclick;
inputcCtrls[m].onclick = window.location = "http://www.google.com/";
would need to be in parenthesis as the if statement only applies to the next line of code, so the following would work
if(inputcCtrls[m].type=='button'&&inputcCtrls[m].value=='Finish')
{
var funcOnClick = inputcCtrls[m].onclick;
inputcCtrls[m].onclick = window.location = "http://www.google.com/";
}
Edit thanks to graham's answer.
Change:
for(var m=0; m<inputcCtrls.length; m++)
if(inputcCtrls[m].type=='button'&&inputcCtrls[m].value=='Finish')
var funcOnClick = inputcCtrls[m].onclick;
inputcCtrls[m].onclick = window.location = "http://www.google.com/";
to
for(var m=0; m<inputcCtrls.length; m++) {
if(inputcCtrls[m].type=='button'&&inputcCtrls[m].value=='Finish') {
var funcOnClick = inputcCtrls[m].onclick;
inputcCtrls[m].onclick = function () { window.location = "http://www.google.com/" };
}
}
onclick wants a function. This is why I always use parathesis no matter if it's one line or not.
It's easier to assign a unique class name to the button and use document.getElementsByClassName than it is to loop through all the inputs to get the right one.
var inputcCtrls = document.getElementsByClassName("finalButton");
inputcCtrls[0].onclick = function() {
window.location = "http://www.google.com/";
}
i want to get the id from the url bar and insert it into the href
$("a[href='send_message.php?act=pm&id=$id']").colorbox({width:"500", height:"350", iframe:true});
there's a jquery plugin to make this ridiculously simple:
see: http://plugins.jquery.com/project/query-object
e.g.
var id = $.query.get('id');
$("a[href='send_message.php?act=pm&id="+id+"']").colorbox({width:"500", height:"350", iframe:true});
For those not using jQuery or any other JS library:
var searchString = document.location.search;
// strip off the leading '?'
searchString = searchString.substring(1);
var gvPairs = searchString.split("&");
var getVars = [];
for (i = 0; i < gvPairs.length; i++)
{
var gvPair = gvPairs[i].split("=");
getVars[gvPair[0]] = gvPair[1];
}
So if the URL string was index.php?id=3&page=2&display=10 then:
getVars['id'] = 3;
getVars['page'] = 2;
getVars['display'] = 10;