Bill Raynor
Bill Raynor

Reputation: 83

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?

Upvotes: 8

Views: 724

Answers (2)

Tschallacka
Tschallacka

Reputation: 28722

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.

Upvotes: 3

Jonathon Hibbard
Jonathon Hibbard

Reputation: 1546

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.

Upvotes: 7

Related Questions