Dynamically generated href won't show properly - javascript

So I'm trying to make this link appear on my page, but it won't return the /register path, it'll just go immediately the UTMs.... On the site it'll show the href as
domain.com/?utm_campaign...
instead of
domain.com/register?utm_campaign...
Why is that and how can that be fixed?
<script>
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
// get the required parameter
const campaign = urlParams.get('utm_campaign');
const source = urlParams.get('utm_source');
const medium = urlParams.get('utm_medium');
var registerationURL = new URL('../register?utm_campaign=&utm_source=&utm_medium=');
registerationURL.searchParams.set('utm_campaign', campaign);
registerationURL.searchParams.set('utm_source', source);
registerationURL.searchParams.set('utm_medium', medium);
var a = document.getElementbyID('test').innerHTML;
a.href = registerationURL;
</script>
<a id="test" href="#">Click here</a>

document.getElementbyID('test').innerHTML returns the string "Click here". Remove the .innerHTML and it should work.
However, this can be done much simpler with the following
var registrationUrl = location.origin + '/register' + location.search;

Related

Appending current URL parameters onto anchor link

At a page like
https://www.example.com/?firstname=Steven&lastname=Smith&email=steve%40gmail.com&phone=0404555555
I have a button (anchor link) #ptsBlock_553944 .ptsCell:nth-of-type(1) .ptsEditArea.ptsInputShell that links to https://www.example.com/form
I'd like to append the URL parameters from the current URL to the button's URL, so that the button's href is now https://www.example.com/form/?firstname=Steven&lastname=Doig&email=steve%40gmail.com&phone=0404555555
How can I do this with JavaScript please?
Use window.location.search:
var url = "https://exmaple.com";
var newurl = url + window.location.search;
newurl will contain all the get (ex. ?something=something&something2=something5) data.
To change the href of a:
var button = document.getElementById('#ptsBlock_553944');
button.href = button.href + window.location.search;
If you don't care about supporting older browsers you can use the URL API and URLSearchParams.
function appendCurrentUrlSearchParams(anchorElement) {
const currUrlSearchParams = new URL(window.location.href).searchParams;
const link = new URL(anchorElement.href);
// uncomment this line if you want to clear query parameters already present in the anchor url
// link.search = '';
for (const entry of currUrlSearchParams.entries()) {
link.searchParams.append(entry[ 0 ], entry[ 1 ]);
}
anchorElement.href = link.href;
}
Usage in your case:
appendCurrentUrlSearchParams(document.querySelector('#ptsBlock_553944 .ptsCell:nth-of-type(1) .ptsEditArea.ptsInputShell'));
Read Html select using select to change the link of a button with Javascript
specifically the section on
Get the element with something like document.getElement MDN getElement Link
Change the .href of that element to what you want.
function selectFunction() {
var x = document.getElementById("selectopt").value;
document.getElementById("mylink").innerHTML = x;
document.getElementById("mylink").href = "http://www." + x + ".com";
}
document.location.pathname = '/questions/69240453/appending-
current-url-parameters-onto-anchor-link/69240510';
//get the document pathname I chose from document.location
let data = document.location.pathname;
let preUrlString = 'www.example.com/form';
let newString = preUrlString + data;
console.log(newString);
'www.example.com/form/questions/69240453/appending-
current-url-parameters-onto-anchor-link/69240510'
document.getElementById("mylink").href = newString;

windows URLSearchParams when changed

My English is not good sorry,
I do not want to let one of the URLSearchParams change.
And when the URLSearchParams is changed, returne to the my input value.
URL address : example.com/action.php?id=1&name=john&penalty=365
<input name='penalty' value='365' hidden>
<script>
$(document).ready(function() {
const url = window.location.href;
const paramspenalt = new URLSearchParams(url.split('?')[1]);
var penaltyvar = $('input[name=penalty]').val();
paramspenalt.set('penalty', penaltyvar);
const resultpenalty = paramspenalt.toString();
window.location = 'action.php?'+resultpenalty+'';
});
</script>
Everything is fine with this code, But the page is constantly loading.
It is very good if the page is loaded only once.
#ksav helping me and
fixed my problem from How do I modify the URL without reloading the page?
:
<input name='penalty' value='365' hidden>
<script>
$(document).ready(function() {
const url = window.location.href;
const paramspenalt = new URLSearchParams(url.split('?')[1]);
var penaltyvar = $('input[name=penalty]').val();
paramspenalt.set('penalty', penaltyvar);
const resultpenalty = paramspenalt.toString();
//****
window.history.pushState("object or string", "Title", 'action.php?'+resultpenalty+'');
//****
});
</script>

Replace with html tag in javascript

I want to replace any text like this in input: [www.Link-to-be-shortened.com]following link(cut)
I want to replace it with following linkby javascript
I have tried this code :
var UserString = " Hi <br>This article is good , Please visit the following link [www.Link-to-be-shortened.com]following link(cut)";
var SystemString = UserString.replace("[", "");
SystemString = SystemString.replace("]following link(cut)", "");
var a = document.createElement('a');
var linkText = document.createTextNode("following link");
a.appendChild(linkText);
a.title = "following link";
a.href = "http://cuer.esy.es/?f="+SystemString;
document.body.appendChild(a);
But this code does not work well
Here's a simple example of how to do this with a regular expression:
var UserString = "[www.Link-to-be-shortened.com]Click here(cut)";
var link = UserString.replace(/\[([^\[]+)\]([^(]+)\(cut\)/g, '$2');
console.log(link);
HOWEVER, this will not work in all possible cases. You could use this if only trusted people are submitting links.

How to split a string and then embed the second string (link) into the first string?

I'm fairly new to JavaScript and I have this RSS Feed I'm working with currently.
When I retrieve an item from the RSS feed, the following is displayed
Google Home Page http://www.google.com
How can I split this string, so that I can embed the second part of it (http://www.google.com) into the first part(Google Home Page)?
First - exclude the link by using following RegEx pattern (searches for string which starts with http://).
/http:\/\/.*[^\W+]/g
The matched value (Array) is being stored into url, now we are able to create the anchor element. (the value of href is the element 0 inside our matches array).
The link content is being generated by replacing the URL with empty space inside the retrievedResult. trim() is optional, I've used it just to remove remaining space.
retrievedResult.replace(url[0], "").trim()
Finally you can append the built anchor element.
var retrievedResult = "Google Home Page http://www.google.com";
var re = /http:\/\/.*[^\W+]/g;
var url = retrievedResult.match(re);
var anchor = '' + retrievedResult.replace(url[0], "").trim() + '';
$('body').append(anchor);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Okay, so this will be the string:
var string = "Google Home Page http://www.google.com";
Then we split it:
var split = string.split('http'); // ['Google Home Page ', '://www.google.com']
Then we create an a element:
var a = document.createElement('a');
Then we add the link as the href attribute of your anchor element:
a.href = 'http' + split[1];
And then we add the text as textContent of your anchor element:
a.textContent = split[0];
And finally we add the element to the body:
document.body.appendChild(a);
Here an example:
var string = "Google Home Page http://www.google.com";
var split = string.split('http');
var a = document.createElement('a');
a.href = 'http' + split[1];
a.textContent = split[0];
document.body.appendChild(a);
You can use jquery to get to your result
Working Example:
//This is HTML part
<div id="linkcontainer"></div>
<input id="str" value='Google Home Page http://www.google.com'>
<a id="createlink">CreateLink</a>
//This is js part
$('#createlink').click(function(){
createLink();
});
//function that makes link
function createLink(){
var str = $('#str').val();
var http = str.indexOf('http');
var url = str.substring(http);
var text = str.substring(0,http);
$('#linkcontainer').html(''+text+'');
}
Try this code on jsfiddle

Getting Parent URL using document.referrer

I'm trying to figure out how to get the second slash or page of a website using the document.referrer javascript
for example the website is www.mysite.com/page1/subpage/subpage2/
I only need to get www.mysite.com/page1/
var url = document.referrer;
var referrer = url.match(/:\/\/(.[^/]+)/)[1];
this only gets me the domain. I need the second page. Any help would be great.
Thanks
Hope this does what you need:
function getReferrerSecondPage() {
var link = document.createElement("a");
link.href = document.referrer;
return link.pathname!="" ? [link.host, link.pathname.split("/")[1]].join("/") : link.host;
}
var referrerSecondPage = getReferrerSecondPage();
Modified your code:
var url = document.referrer;
var referrer = url.match(/(http:)\/\/(.[^/]+)\/([^./]+)/)[0];
// Display
var foo = document.getElementById("foo");
foo.innerHTML = referrer + "/";
<p id="foo"></p>

Categories