New line character in output file - javascript

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>

Related

Result of element is changing during getting it by script

I tried to get data with JavaScript:
The Text
var link = document.getElementById('link_Page')
var text=link.innerHTML;
var href=link.href;
I expect to see:
"/product/23" and "The Text "
But result is:
"http://localhost:60790/product/23" and "The Text "
Note: on jsfiddle.js I tested and result of text(not link) was fine. couldn't understand why it's gives me ' '
https://jsfiddle.net/mahma/ocwnufqb/
Note: on jsfiddle.js I tested and result of text(not link) was fine
.href will return the full URL of the linked resource, to get the exact value of the href attribute try using Element.getAttribute():
var link = document.getElementById('link_Page')
var text=link.innerHTML;
var href=link.getAttribute('href');
console.log(text);
console.log(href);
The Text
is the space character in HTML. You have a space character in the end of the a tag's text.
Here is the way you can do what you want.
var link = document.getElementById('link_Page')
var text = link.innerText;
var href = link.getAttribute('href');
console.log(text, href);
The Text

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.

Downloading file made with jquery's .innerhtml breaks at the first "#"

I have this code:
function download()
{
var a = document.body.appendChild(document.createElement("a"));
a.download = "CalExport.svg";
var dd = document.getElementById('SvgResult');
alert(dd.innerHTML); //displays fine
a.href = "data:image/svg+xml," + dd.innerHTML;
a.click();//downloaded file cuts off at the first "#"
}
When the alert displays it it's okay, the downloaded version is cut off before the first "#". How do I fix this?
Since this is part of a href, you need to url-encode your data first, eg.
function download()
{
var a = document.body.appendChild(document.createElement("a"));
a.download = "CalExport.svg";
var dd = document.getElementById('SvgResult');
alert(dd.innerHTML); //should still display fine
a.href = "data:image/svg+xml," + encodeURIComponent(dd.innerHTML);
a.click();//should now not cut off.
}
The safe variation of # in a url is %23%0A (check out this tool: http://meyerweb.com/eric/tools/dencoder/).

create a downloadable csv from a json string

Target: write&download a csv file starting with a json string, for example data.csv containing
col1,col2,col3
"324","19-08-2014","13000"
"325","19-08-2014","5010"
What I have done until now:
1) iframe and button to call my conversion function
<iframe id="frame" style="display:none"></iframe>
<form><input type="submit" value="Export CSV" onclick="javascript:Download();"></form>
2) my Download() function which would want to download my csv file
<script type="text/javascript">
function Download(){
var csv=ConvertToCSV(<?php echo $json_string ?>);
var url='data:application/csv,'+csv;
var _iframe_dl = $('<iframe />')
.attr('src', url)
.hide()
.appendTo('body');
};
</script>
3) my json to csv conversion function which tries to create a csv string
<script type="text/javascript">
function ConvertToCSV(json) {
var array = typeof json != 'object' ? JSON.parse(json) : json;
var str = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
if (line != '') line += ','
line += '"'+array[i][index]+'"';
}
str += line + "\r\n";
}
return str;
}
</script>
Encountered problems :
i) it seems that it doesn't recognize \r\n, infact output is just one line
"324","19-08-2014","13000""325","19-08-2014","5010"
ii) I cannot set the filename and the extension, infact the downloaded file is "download" without extension containing the single line mentioned above
First of all, you will need to ensure your data is in this format, like the example below.
var array = [["col1","col2","col3"],["324","19-08-2014","13000"],["324","19-08-2014","13000"]]
then you need to create csv variable as shown below
var csv = "data:text/csv;charset=utf-8,";
after this you need to loop through your data array and append each line to the csv variable you just set.
array.forEach(function(arrayItem, index){
arrayAsString = arrayItem.join(",");
csv += index < array.length ? arrayAsString+ "\n" : arrayAsString;
});
now to give this file a name and create a download link you must create a hidden anchor node and set its download attribute.
var encUri = encodeURI(csv);
var link = document.createElement("a");
link.setAttribute("href", encUri);
link.setAttribute("download", "file_name.csv");
//add anchor element to body
document.body.appendChild(link);
link.click();
EDIT:
Tested on Chrome and is working, also on Safari. Does not work on Firefox for some reason which i will take a look at now
I found out that if you add the link into the body of the page only then will Firefox initiate the download, you can use a code like so. I have updated my code above
document.body.appendChild(link);

Use jQuery to get the file input's selected filename without the path

I used this:
$('input[type=file]').val()
to get the file name selected, but it returned the full path, as in "C:\fakepath\filename.doc". The "fakepath" part was actually there - not sure if it's supposed to be, but this is my first time working with the filename of file uploads.
How can I just get the file name (filename.doc)?
var filename = $('input[type=file]').val().split('\\').pop();
or you could just do (because it's always C:\fakepath that is added for security reasons):
var filename = $('input[type=file]').val().replace(/C:\\fakepath\\/i, '')
You just need to do the code below. The first [0] is to access the HTML element and second [0] is to access the first file of the file upload (I included a validation in case that there is no file):
var filename = $('input[type=file]')[0].files.length ? ('input[type=file]')[0].files[0].name : "";
Get path work with all OS
var filename = $('input[type=file]').val().replace(/.*(\/|\\)/, '');
Example
C:\fakepath\filename.doc
/var/fakepath/filename.doc
Both return
filename.doc
filename.doc
Chrome returns C:\fakepath\... for security reasons - a website should not be able to obtain information about your computer such as the path to a file on your computer.
To get just the filename portion of a string, you can use split()...
var file = path.split('\\').pop();
jsFiddle.
...or a regular expression...
var file = path.match(/\\([^\\]+)$/)[1];
jsFiddle.
...or lastIndexOf()...
var file = path.substr(path.lastIndexOf('\\') + 1);
jsFiddle.
Here is how I do it, it works pretty well.
In your HTML do:
<input type="file" name="Att_AttributeID" onchange="fileSelect(event)" class="inputField" />
Then in your js file create a simple function:
function fileSelect(id, e){
console.log(e.target.files[0].name);
}
If you're doing multiple files, you should also be able to get the list by looping over this:
e.target.files[0].name
maybe some addition for avoid fakepath:
var fileName = $('input[type=file]').val();
var clean=fileName.split('\\').pop(); // clean from C:\fakepath OR C:\fake_path
alert('clean file name : '+ fileName);
How about something like this?
var pathArray = $('input[type=file]').val().split('\\');
alert(pathArray[pathArray.length - 1]);
This alternative seems the most appropriate.
$('input[type="file"]').change(function(e){
var fileName = e.target.files[0].name;
alert('The file "' + fileName + '" has been selected.');
});
Does it have to be jquery? Or can you just use JavaScript's native yourpath.split("\\") to split the string to an array?
<script type="text/javascript">
$('#upload').on('change',function(){
// output raw value of file input
$('#filename').html($(this).val().replace(/.*(\/|\\)/, ''));
// or, manipulate it further with regex etc.
var filename = $(this).val().replace(/.*(\/|\\)/, '');
// .. do your magic
$('#filename').html(filename);
});
</script>
Get the first file from the control and then get the name of the file, it will ignore the file path on Chrome, and also will make correction of path for IE browsers. On saving the file, you have to use System.io.Path.GetFileName method to get the file name only for IE browsers
var fileUpload = $("#ContentPlaceHolder1_FileUpload_mediaFile").get(0);
var files = fileUpload.files;
var mediafilename = "";
for (var i = 0; i < files.length; i++) {
mediafilename = files[i].name;
}
Here you can call like this
Let this is my Input File control
<input type="file" title="search image" id="file" name="file" onchange="show(this)" />
Now here is my Jquery which get called once you select the file
<script type="text/javascript">
function show(input) {
var fileName = input.files[0].name;
alert('The file "' + fileName + '" has been selected.');
}
</script>
var filename=location.href.substr(location.href.lastIndexOf("/")+1);
alert(filename);
We can also remove it using match
var fileName = $('input:file').val().match(/[^\\/]*$/)[0];
$('#file-name').val(fileName);

Categories