Django. Jquery. escaping string with quotes error - javascript

In a small forum, any user can save posts. Sometimes those posts include words surrounded by quotes ( " " ). This gives me an error when I try to handle those strings with javascript.
I wrote some jquery code that uses the django variable like this:
new_text = "{{text|safe}}";
$("#text_p").text(new_text);
if I mark it as "safe" then javascript gives me a syntax error:
the text "(error here)word between quotes" the user posted
This is logical because javascript understands the quotes like this:
new_text = "this is the text "word between quotes" the user posted"
So, if I don't mark it as "safe" and let django escape the text, it doesn't give me an error, but the text looks like this:
the text "word between quotes&quot the user posted
I don't know what to do, and I guess it may not be simple cause if I use single quotes to declare the javascript variable, I will have the same problem when the user posts a text with single quotes. If I use a regex to replace double quotes and not mark the text as "text|safe", then other tags will be escaped and the text will be full of "<br /&gt" etc.
I have an idea that may work but is ugly and probably not the best option:
including the text in a <p class = "hidden"> tag and then calling it using jquery.
So, the question is, how do I solve this?, is there a better way?
Thanks in advance for your help.
EDIT:
I created a Runnable to explain it better.

Use escapejs filter.
Example:
{{ string|escapejs }}

Ok, I found a partial solution, hope it helps someone in the future. It is not an elegant solution, so, if anyone has a better option, it will be welcomed.
I included the text that has a "quoted" word inside a html hidden tag.
python-django:
text_with_quotes = 'this is a text and a word between "quotes"'
html:
<p id = "new_text" class = "hidden"> {{text_with_quotes|safe}}</p>
js:
new_text = $("#new_text").text();
$("#text_p").text(new_text);
it works. But there may be a better option using javascript and/or python.

Related

Multiple use of backticks within Javascript

I'm having some trouble using backticks and I'm wondering if anyone can help me. I have the code below which allows me to output multiple responses. The trouble is, when I put a comma after target="_blank">here` it doesn't allow me to add further phrases. I have attempted using a backspace before the backtick to break out of it but no luck. Here is my code, I'm using Javascript and HTML.
<script>
function talk(){
var know ={
"How does this work":"I can help you find what you're looking for.",
"how does this work":"I can help you find what you're looking for.",
"contact":`You can contact us by clicking here`
};
var user = document.getElementById('userBox').value;
document.getElementById('chatLog').innerHTML = user + "<br>";
if(user in know){
document.getElementById('chatLog').innerHTML = know[user] + "<br>";
}else{
document.getElementById('chatLog').innerHTML = "I do not understand.";
}
}
</script>
To clarify, I'm needing something like this: (but obviously the comma doesn't work)
"How does this work":"I can help you find what you're looking for.",
"how does this work":"I can help you find what you're looking for.",
"contact":`You can contact us by clicking here`,
"help":`You can find help by clicking here`
As you know the use of " & ' should corresponded to each other
Double quotes around attribute values are the most common in HTML, but single quotes can also be used.
In some situations, when the attribute value itself contains double quotes, it is necessary to use single quotes:
<p title='John "ShotGun" Nelson'>
Or vice versa:
<p title="John 'ShotGun' Nelson">
The backslash (\) escape character turns special characters into string characters .
If there are extra symbols in between you can use \ backslash before them so that they don't interfere with the code and treated as symbols like this :
<p title="John \'ShotGun\' Nelson you\'re a good\\bad person">
It will be displayed like this :
John 'ShotGun' Nelson you're a good\bad person
Refer to this for more about backslash

Javascript - break in textarea but not in paragraph

I have a question:
I have a QR Code Scanner which gets a VCard. Im getting back the following String:
BEGIN:VCARD VERSION:2.1 FN:John Doe N:doe;john END:VCARD
The problem is the following: When putting this Information (via Javascript) in a textarea or just dump it to an alert winow, the information has breaks in between, looking like this:
BEGIN:VCARD
VERSION:2.1
FN:John Doe
.
.
.
But when putting this information into a paragraph (<p></p>), it has no breaks in it and it's just a plain string.
The question is now, can I put those breaks into the paragraph as well or can I insert another sign or anything else in between the attributes?
I thought about just splitting the string on blanks, but it's not working because e.g. FN itself contains blanks as wel...
Thanks for your help.
Edit:
Unfortunatelly, all 3 advices don't work..
What I have now is the following:
function writeqrcodecontent(){
var textfeld = document.getElementById("inhaltvonqrcode");
var wert = $.scriptcam.getBarCode();
//wert.split('\n').join('<br/>');
//wert.replace("\n", "<br>");
//wert.replace(/\n/g,'<br>');
textfeld.innerHTML = wert;
textfeld.style.display="block";
}
But as said, all three commented out lines do not work, everything is still displayed in one line.
The paragraph is defined with:
<p id="inhaltvonqrcode" style="display:none; clear:both;"></p
I understand your ideas but I don't understand why it's not working...
By the way, what I also tried is something like wert.split('\n').join('#'); to see, if it's really the break or it's just not working, but this doesn't work as well, so the text just seems to have no \n in it..
EDIT 2
It's working now, I neeeded to do both steps in one step, so not
var wert = $.scriptcam.getBarCode();
wert.split('\n').join('<br/>');
but
var wert = ($.scriptcam.getBarCode()).split('\n').join('<br/>');
Thanks for your help!
The string you get back likely contains newline characters \n. To get them to display with the newlines intact in HTML, you can either wrap everything returned with <pre></pre> in your HTML. Or split on newline \n and replace it with <br />.
text.split('\n').join('<br />')
text.replace(/\n/g,'<br>');
this line will replace all lines with <br />
Your barcode reader is reading the vCard with \n newline, however the pure html this newline is ignored.
in Javascript you can just use something like
someText.replace("\n", "<br>");
and it will do what you want. In php its the nl2br function

Using script to find string of text up until first html tag

I have a service that is returning a message. That message may be a combination of plain text or an html formatted text.
ex1: "This is a message"
ex2: "<p> This is also a message <p/>"
ex3: "This is also a <strong> message </strong>"
The thing we would like to do is come up with a script that would return as much plain text up until the first tag. So in the examples above:
would return "This is a message.
would return ""
would return "This is also a"
I am not sure what approach is the best to do this. Can i accomplish this using Regex or JS. I know Regex can easily return text between two tags, but what i am looking for is a little different. Thanks in advance for any advice or help.
The simplest solution would be to match anything except <s, starting at the beginning of the string:
match = subject.match(/^[^<]*/)[0];
This fails if <s could occur in comments/quoted strings before the first HTML tag, but that might not be a problem.
Test on JSFiddle
Explanation:
^ # Anchor the match to the start of the string.
[^<] # Match any character that's not a <
* # zero or more times (as many as possible).

Title Tag With Quotes & Apostrophe ( " & ' ) For Insertion In DB

I've been searching for a solution to be able to have the following:
a
so the tooltip shows up as: what's the big "DEAL" about "double quotes" & 'single' ones
So the user inputs their text in a dialog box and I'm using js to parse the text, put it in the wysiwyg (tinymce) and then send to db.
Here's what I've tried:
encodeURIComponent gives me:
what's%20the%20big%20%22DEAL%22%20about%20%22double%20quotes%22%20%26%20'single'%20ones
this doesn't solve it because when I take the data out of mysql and dump it back on the page I'm back to the original because I use url decode on the whole text (this I cannot change).
Tried escaping the quotes with regex like:
title.replace(/'/g, "\\'");
title.replace(/"/g, '\\"');
This worked on 'single' quotes but not double
What I get back is title="what\'s the big \" (note I'm using a prepared statement in php to insert this into the db)
I've researched escaping strings and certain characters in js or encoding them so for example " becomes " but all I get stuff that requires you to build your own functions. Is this the case?
My questions is this:
Am I missing something? Is there a more elegant solution to this? How would you recommend I do it? Where in the process should this be done?
I've seen this (How to escape double quotes in title attribute) but this doesn't explain how to create a robust solution for handling constantly changing user content (and title attribute).
Thank you all.

Is there a javascript module to format user text input into proper "english" format?

I am looking for a text formatter that will take user input from a textbox and add in newlines and stuff.
The current way I'm doing it is to push the text into a function and replace specific regex matches with their html counterparts:
function textformatter(text) {
var urlRegex =/[\n\r]/g;
return text.replace(urlRegex, function(text) {
return '<br/>';
});
}
I'd have to add a new regex match for each thing I want to replace i.e. italics, bolds, etc. Thought I'd try to find a module out there because this seems like a common thing to do and someone might've written something much better than what I'd write.
Tried to google but I guess my search words are incorrect?
Thanks, in advance.
I'm not exactly clear what you want the intended output to be? ("add in newlines and stuff"), but have you looked at markdown?
It's a light-weight markup language lets you write mostly in plain text and get formatted html as an output. All the markup is supposed to be plain-text readable (for example, bold is done with asterisks). In fact, StackOverflow comments/answers/questions are written in a markdown dialect! And you'll definitely be able to find a markdown converter for whatever language you want. Here's a js markdown parser.
In any case, it's hard to answer without knowing more about what you need. What is text in the function you're calling? Is it plain text from a textarea? Besides replacing new lines with <br>, what formatting do you want to be done?
As mentioned, Markdown would be the right thing to use for text, but if you simply want to escape unsafe characters, the javascript method encodeURIComponent could be used.
http://www.w3schools.com/jsref/jsref_encodeuricomponent.asp

Categories