Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hashtag within string breaks JavaScript

I am trying to save a string to an external file using JavaScript. Below is what I am executing.

var mytext = "1111#1111"
var a = document.body.appendChild(document.createElement("a"));
a.download = "My_output.html"; 
a.href = "data:text/html," + mytext; 
a.click();

This code works perfectly using Chrome. However with Firefox, it stops just prior to the "#". When I look at the resulting output file I see the following:

Results in Chrome look like this 1111#1111

Results in Firefox look like this 1111

It looks to me like the hashtag is breaking something. Can anyone help me understand why the "#" in a string is causing grief in Firefox but not Chrome? I have tried wrapping the string in double quotes as well as single quotes, but it does not appear to have any effect.

Any ideas?

like image 613
Bill Raynor Avatar asked Aug 03 '15 14:08

Bill Raynor


2 Answers

You need to add URL Encoding to your string before you submit it.

var mytext = encodeURIComponent( "1111#1111" );
var a = document.body.appendChild(document.createElement("a"));
a.download = "My_output.html"; 
a.href = "data:text/html," + mytext; 
a.click();

More information can be found here: encodeURIComponent

EDIT: And, this is just me btw, but why would you even do data:text/html? Just seems unnecessary.

You could just as easily submit this via Ajax (or use jQuery's $.ajax if you have that library available). If you happen to use jQuery, then all of this might be a little easier. Either way, hope that helps.

like image 82
Jonathon Hibbard Avatar answered Oct 05 '22 15:10

Jonathon Hibbard


If I use this in firefox it comes out fine

var mytext = encodeURIComponent("1111#1111");
var a = document.body.appendChild(document.createElement("a"));
a.download = "My_output.html"; 
a.href = "data:text/html," + mytext; 
a.click();

The trick is as always to encode uri components. And what you are passing along is in essense an uri component.

This way all special characters like ? # and + and % will be parsed correctly.

like image 33
Tschallacka Avatar answered Oct 05 '22 16:10

Tschallacka