HTML and JavaScript - How to save plain text right - javascript

I want to save a locally generated textfile.
This code almost does what I want:
<a download="filename.txt" href="data:text/plain,sometext">Download</a>
sometext represents a string in that tag attribute (inserted using javascript).
You could imagine it as the content of a textarea which is set by the user.
The problem is that sometext must not contain " or ' because otherwise the href attribute thinks that its content finishes earlier which causes the tag to just save a part of that string when you click on it.
As sometext is generated by the user, it can contain these characters and I do not want to force the user to not use these.
Is there another way to save text files using html/javascript?
I do not want to send sometext to the server. (Which would solve the problem because I could create a file there (including " and ') and feature a download link)

It will depend on how are you adding this something to the href.
First of all, a single quote wont matter, because it is wrapped by double quotes ", so it will work well like this:
Download
When it comes to double quotes, in the HTML context you would have to use the correct notation, in this case it would be ". The HTML will understand it as double quotes:
Download
<!-- It will turn into mytext"text -->
However
Since you said that it will be an user's input, I suppose you might be setting the href through Javascript, so I don't think it would matter, it would be like this:
(Try typing single or double quotes... For JS it won't matter)
var ChangeHref = function() {
var el = document.getElementById("a1");
el.href = "data:text/plain," + document.getElementById("inp1").value;
}
<input id="inp1" type="text" />
<input type="button" value="change href" onclick="ChangeHref()" />
<br />
<a id="a1" download="filename.txt" href="data:text/plain,test">Download</a>

Write a simple javascript to remove ' and " characters like so
userText.replace(/\'/g, '').replace(/\"/g, '');
The / means its a regex, the \' and \" represent the literal characters ' and " and the g at the end makes it find all to occurrences to replace.
But since you want to keep it then do this:
userText.replace(/\'/g, '\\\'').replace(/\"/g, '\\\"');
The \ is a literal backslash. that way when you add it to the name of the file it will escape out and mean a literal ' and ".

Related

How do I take a block of text (with `\n`) from an object property and parse it as paragraphs?

The property is like this.
key: "paragraph.\n More text.\n Another sentence."
How would I show it like...
paragraph.
More text.
Another sentence.
without iterating or split()ting the text?
Number of paragraphs will be unknown at time of read. I have access to the object to rewrite the text in some other format, but it needs to stay as a single property.
I've tried
<p>{item["instruction"]}</p>
<p>{item.instruction}</p>
which both return solid blocks.
You can use for example css 'white-space':
<p style="white-space: pre-line;">{item.instruction}</p>
Or depending on what template library you use replace \n sign with <br /> tag (but most template libs escape html when rendering the value).
you can replace all \n in your string with <br /> element
for replace all \n in your string you must use RegExp in replace method.
var key = "paragraph.\n More text.\n Another sentence."
// put result of this command in your html element
key.replace(/\n/g,'<br />')

How to avoid HTML text from breaking when inserted in input's value?

I would like to replace my hidden input's value with some html text and send it to the server as plain text. Here's how I did :
$('#div').append("<input type="hidden" value='<div><h1>Some text</h1><svg ...></svg></div>'");
The problem is that the code breaks and displays the value of the input as HTML tags into my template, which makes it unusable to the backend when sent.
Here's the jsfiddle: https://jsfiddle.net/Lindow/9p77afc3/2/, while inspecting you'll see that the svg got out of the input's value, that's what I'm trying to avoid.
How can I resolve this issue?
Your input element is not hidden. Provide it with the type="hidden" attribute.
After you added that to your question you have a problem with not escaping quotes. Escape those inner double quotes with backslash, or use single quotes:
$('#div').append("<input type='hidden' value='<div><h1>Some text</h1><svg ...></svg></div>'");
After the next edit, which added the fiddle, it shows you have single quotes in the svg content, and that you do not quote the value property's value.
Do it like this:
$('.elements').append("<div>hey : <input hidden value=\"" + "<svg ... </svg>" + "\"</div>");
// ^^ ^^
Corrected fiddle: https://jsfiddle.net/9p77afc3/4/
Need to change single quotes instead of double quotes.
Try below:
$('#div').append("<input type='hidden' value='<div><h1>Some text</h1><svg ...></svg></div>'");

Replacing apostrophe in string

I'm using phonegap to share an article via WhatsApp.
The code for the button is as follows:
shareArticle += '<li class="rrssb-whatsapp"><a href="javascript: void(1)" onclick="window.plugins.socialsharing.shareViaWhatsApp(\''+$('.article_title').html().replace(/'/g, "&apos;")+'\', null, \'http://www.myaddress.com/showArticle-'+articleId+'\', function() {console.log(\'share ok\')}, function(errormsg){alert(errormsg)});" class="popup" data-action="share/whatsapp/share">';
shareArticle += '<span class="rrssb-icon"><!-- Icon in SVG --></span>';
shareArticle += '</a></li>';
The part that I'm asking about is this:
onclick="window.plugins.socialsharing.shareViaWhatsApp(\''+$('.article_title').html().replace(/'/g, "&apos;")+'\', null, \'http://www.myaddress.com/showArticle-'+articleId+'\', function() {console.log(\'share ok\')}, function(errormsg){alert(errormsg)});"
The button is not working when there is an apostrophe in the title.
The strangest thing is that if I replace &apos; with " it work perfectly (even thought the result is wrong).
Doe's anybody has any idead why &apos; fails?
Thank you all for your support.
The solution is to change the apostrophe to another sign that doesn't break the string.
So what I did is:
$('.opinion_content_title').html().replace(/'/g, "′")
Again, thank you all.
The named character reference &apos; (the apostrophe, U+0027) was introduced in XML 1.0 but does not appear in HTML. Authors should therefore use ' instead of &apos; to work as expected in HTML 4 user agents.

HTML textarea ignores 1st new line character, why?

Could you explain why this:
<script type="text/javascript">
document.write("<textarea cols='10' rows='10'>" + "\nhello\nbabe\n" + "</textarea>");
</script>
renders a textarea with one new line at the bottom, but NO new line at the top?
Tested IE8, FF11, Safari 5.1, Chrome 24
And it's not a JS issue, even when you write HTML in page you get the same result, i.e.
<textarea cols='10' rows='10'>
hello
babe
</textarea>
The 1st new line is still missing!!!
I need to add another new line at the top in order to show one:
document.write("<textarea cols='10' rows='10'>" + "\n\nhello\nbabe\n" + "</textarea>");
When writing inside of XHTML use proper entities.
<textarea>
hello</textarea>
If a text node begins with white space (space, new line) it will be ignored by HTML parsers. Encoding the new line into a proper HTML entity forces the parser to acknowledge it.
== carriage return
Answering the question "Why". This is specified in HTML 5 specification in the chapter that describes how DOM tree is created from tags found in a HTML document.
In the current HTML 5 living standard it is "12.2 Parsing HTML documents" > "12.2.6 Tree construction" > "12.2.6.4 The rules for parsing tokens in HTML content" > "12.2.6.4.7 The "in body" insertion mode".
(In HTML 5.2 the same section is numbered 8.2.5.4.7).
Scroll down for item "A start tag whose tag name is "textarea""
A start tag whose tag name is "textarea"
Run these steps:
1. Insert an HTML element for the token.
2. If the next token is a U+000A LINE FEED (LF) character token, then ignore that token and move on to the next one. (Newlines at the start of textarea elements are ignored as an authoring convenience.)
3. Switch the tokenizer to the RCDATA state.
...
The algorithm deals with LF characters only, because CR characters are handled earlier.
(Historically, looking into obsolete HTML 4.01 specification:
Its Chapter 17.7 "The TEXTAREA element" has an example that shows that text content for a textarea starts from a new line.
Appendix B.3.1 Line breaks (informative) explains that such behaviour originates from SGML.)
A line break character before </textarea> end tag is not ignored nowadays, in HTML 5.
If possible, change your code to have the textarea pre-defined as html, then write the string like this instead:
HTML:
<textarea cols='10' rows='10' id='test'></textarea>
Script:
document.getElementById('test').innerHTML = '\nhello\nbabe\n';
That should preserve white-space. Optionally you can add a css rule:
textarea {
white-space:pre;
}
A fiddle to play with:
http://jsfiddle.net/RFLwH/1/
Update:
OP tested in IE8 which this does not work - it appear to be a limitation/bug with this browser. IE8 do actually use CR+LF if you manually insert a line-feed at the top, but when set programmatic this is completely ignored by the browser.
Add this to the html to do a test:
<span onclick="this.innerHTML = escape(document.getElementById('test').innerHTML);">
Get textarea content
</span>
You can see the string returned is:
%0D%0Ahello%20babe%20
meaning the CR+LF is there (the other line-feeds are converted to spaces - but inserting a space at the beginning does not help either). I guess there is nothing you can do about this behavior; the browser is obsolete (but unfortunately still widely used so this can be a problem for those users if this is essential).
Add a whitespace before the first "\n" like this :
<script type="text/javascript">
document.write("<textarea cols='10' rows='10'>" + " \nhello\nbabe\n" + "</textarea>");
</script>
or
<textarea cols='10' rows='10'> <!-- whitespace here -->
hello
babe
</textarea>
otherwise it won't work.
Update:
Later in your server side, you can remove the first whitespace by doing
$str = ltrim ($str,' ');
or
$str2 = substr($str, 4);
if it is PHP.
It should be a \n\r at the top:
document.write("<textarea cols='10' rows='10'>" + "\n\rhello\nbabe\n" + "</textarea>");
jsbin
Finally i finished with this server-side solution:
to double leading(only first!) nl symbol before output it in textarea:
if(str_startswith("\r\n",$value))
{
$value = "\r\n".$value;
}elseif(str_startswith("\n",$value))
{
$value = "\n".$value;
}elseif(str_startswith("\r",$value))
{
$value = "\r".$value;
}
function str_startswith($start, $string)
{
if(mb_strlen($start)>mb_strlen($string))
return FALSE;
return (mb_substr($string, 0,mb_strlen($start))==$start);
}

I have a problem with slash in javaScript n Ajax

I have a problem with slash in javaScript n Ajax
I am displaying value dynamically in a span like below:
String num = "37-C110PDD/L";
<span id="p21stk_<%=NUM%>"></span>
in Script:
value for chks[0] is 37-C110PDD/L here the value contains slash and is not displaying the required value in span
Code used in script to update value dynamically:
$("#p21stkArwhed_"+chks[0].value).html($("#qohArrVal_"+chks[0].value).val())
Above code working for parameters without SLASH
Any idea how to solve....?
Thank you..........
Using slashes in the attribute ID is illegal.
See What are valid values for the id attribute in HTML?
You should replace your slash with a valid character, an hyphen ("-") or an underscore ("_") for example.
You can use custom data-* attributes (http://www.w3.org/TR/html5/elements.html#embedding-custom-non-visible-data-with-the-data-attributes), for example:
HTML:
<span data-id="37-C110PDD/L">a span</span>
JS:
alert( $("span[data-id='37-C110PDD/L']").text() );

Categories