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;
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.
I have this you URL passby my variable and somehow I get the URL differently, so I have to remove it.
My URL
http://localhost/Air.com/Img/team/12345/12345.png
I am using this code to remove it
Image_src = url
// Image_src = Image_src.replace(/https?:\/\/[^\/]+\/+/i, "");
But somehow sometimes I have other URL, is there any way I can remove everything before /Img
Img/team/12345/12345.png
No matter what URL in front, remove everything before Img.
Try this:
var Image_src = url.substring(url.indexOf("/Img/"));
If you don't want the / character also just add 1, like so:
var Image_src = url.substring(url.indexOf("/Img/") + 1);
This may help you.
var parser = document.createElement('a');
parser.href = "http://localhost/Air.com/Img/team/12345/12345.png";
parser.pathname.substring(parser.pathname.indexOf('/',2)) // return /Img/team/12345/12345.png
When I try to write a string with multiple lines to an output text file the newline chars are not preserved and all the content is printed on one single line.
In the specific I have a button with a listener on click with associated this function:
function (e) {
this.downloadButton.setAttribute("download", "output.txt");
var textToSend = string1+"\r\n"+string2+"\r\n"+string3;
this.downloadButton.setAttribute('href', 'data:text/plain;charset=utf-8,' + textToSend);
}
The file correctly downloaded, but string1, string2 and string3 are on the same line.
Any suggestion?
I think you may need to encode your data, which you can do with encodeURIComponent().
Try this:
var textToSend = string1+"\r\n"+string2+"\r\n"+string3;
textToSend = encodeURIComponent(textToSend);
this.downloadButton.setAttribute('href', 'data:text/plain;charset=utf-8,' + textToSend)
Use encodeURIComponent(). See working example below.
var downloadButton = document.getElementById('download');
var textToSend = encodeURIComponent("string1\r\nstring2\r\nstring3");
downloadButton.setAttribute('href', 'data:text/plain;charset=utf-8,' + textToSend);
<a id="download" download="output.txt">Download</a>
If we were on a nodeJS server, we could write a header, set a mime type, and send it:
res.header("Content-Disposition", "attachment;filename="+name+".csv");
res.type("text/csv");
res.send(200, csvString);
and because of the headers, the browser will create a download for the named csv file.
When useful data is generated in a browser, one solution to getting it in a CSV file is to use ajax, upload it to the server, (perhaps optionally save it there) and get the server to send it back with these headers to become a csv download back at the browser.
However, I would like a 100% browser solution that does not involve ping-pong with the server.
So it occurred to me that one could open a new window and try to set the header with a META tag equivalent.
But this doesn't work for me in recent Chrome.
I do get a new window, and it contains the csvString, but does not act as a download.
I guess I expected to get either a download in a bottom tab or a blank new window with a download in a bottom tab.
I'm wondering if the meta tags are correct or if other tags are also needed.
Is there a way to make this work without punting it to the server?
JsFiddle for Creating a CSV in the Browser (not working - outputs window but no download)
var A = [['n','sqrt(n)']]; // initialize array of rows with header row as 1st item
for(var j=1;j<10;++j){ A.push([j, Math.sqrt(j)]) }
var csvRows = [];
for(var i=0,l=A.length; i<l; ++i){
csvRows.push(A[i].join(',')); // unquoted CSV row
}
var csvString = csvRows.join("\n");
console.log(csvString);
var csvWin = window.open("","","");
csvWin.document.write('<meta name="content-type" content="text/csv">');
csvWin.document.write('<meta name="content-disposition" content="attachment; filename=data.csv"> ');
csvWin.document.write(csvString);
There's always the HTML5 download attribute :
This attribute, if present, indicates that the author intends the
hyperlink to be used for downloading a resource so that when the user
clicks on the link they will be prompted to save it as a local file.
If the attribute has a value, the value will be used as the pre-filled
file name in the Save prompt that opens when the user clicks on the
link.
var A = [['n','sqrt(n)']];
for(var j=1; j<10; ++j){
A.push([j, Math.sqrt(j)]);
}
var csvRows = [];
for(var i=0, l=A.length; i<l; ++i){
csvRows.push(A[i].join(','));
}
var csvString = csvRows.join("%0A");
var a = document.createElement('a');
a.href = 'data:attachment/csv,' + encodeURIComponent(csvString);
a.target = '_blank';
a.download = 'myFile.csv';
document.body.appendChild(a);
a.click();
FIDDLE
Tested in Chrome and Firefox, works fine in the newest versions (as of July 2013).
Works in Opera as well, but does not set the filename (as of July 2013).
Does not seem to work in IE9 (big suprise) (as of July 2013).
An overview over what browsers support the download attribute can be found Here
For non-supporting browsers, one has to set the appropriate headers on the serverside.
Apparently there is a hack for IE10 and IE11, which doesn't support the download attribute (Edge does however).
var A = [['n','sqrt(n)']];
for(var j=1; j<10; ++j){
A.push([j, Math.sqrt(j)]);
}
var csvRows = [];
for(var i=0, l=A.length; i<l; ++i){
csvRows.push(A[i].join(','));
}
var csvString = csvRows.join("%0A");
if (window.navigator.msSaveOrOpenBlob) {
var blob = new Blob([csvString]);
window.navigator.msSaveOrOpenBlob(blob, 'myFile.csv');
} else {
var a = document.createElement('a');
a.href = 'data:attachment/csv,' + encodeURIComponent(csvString);
a.target = '_blank';
a.download = 'myFile.csv';
document.body.appendChild(a);
a.click();
}
#adeneo answer works for Firefox and chrome... For IE the below can be used.
if (window.navigator.msSaveOrOpenBlob) {
var blob = new Blob([decodeURIComponent(encodeURI(result.data))], {
type: "text/csv;charset=utf-8;"
});
navigator.msSaveBlob(blob, 'FileName.csv');
}
See adeneo's answer, but don't forget encodeURIComponent!
a.href = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csvString);
Also, I needed to do "\r\n" not just "\n" for the row delimiter.
var csvString = csvRows.join("\r\n");
Revised fiddle: http://jsfiddle.net/7Q3c6/
Once I packed JS code doing that to a tiny library:
https://github.com/AlexLibs/client-side-csv-generator
The Code, Documentation and Demo/Playground are provided on Github.
Enjoy :)
Pull requests are welcome.
We can easily create and export/download the excel file with any separator (in this answer I am using the comma separator) using javascript. I am not using any external package for creating the excel file.
var Head = [[
'Heading 1',
'Heading 2',
'Heading 3',
'Heading 4'
]];
var row = [
{key1:1,key2:2, key3:3, key4:4},
{key1:2,key2:5, key3:6, key4:7},
{key1:3,key2:2, key3:3, key4:4},
{key1:4,key2:2, key3:3, key4:4},
{key1:5,key2:2, key3:3, key4:4}
];
for (var item = 0; item < row.length; ++item) {
Head.push([
row[item].key1,
row[item].key2,
row[item].key3,
row[item].key4
]);
}
var csvRows = [];
for (var cell = 0; cell < Head.length; ++cell) {
csvRows.push(Head[cell].join(','));
}
var csvString = csvRows.join("\n");
let csvFile = new Blob([csvString], { type: "text/csv" });
let downloadLink = document.createElement("a");
downloadLink.download = 'MYCSVFILE.csv';
downloadLink.href = window.URL.createObjectURL(csvFile);
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
See adeneo's answer, but to make this work in Excel in all countries you should add "SEP=," to the first line of the file. This will set the standard separator in Excel and will not show up in the actual document
var csvString = "SEP=, \n" + csvRows.join("\r\n");