Django Jquery escape string with quotes

In a small forum, any user can save posts. Sometimes these messages include words surrounded by quotation marks (""). This gives me an error when I try to process these lines using javascript.

I wrote jquery code that uses the django variable as follows:

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 quotes like this:

 new_text = "this is the text "word between quotes" the user posted" 

So, if I do not mark it as β€œsafe” and let django delete the text, this does not 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 think it may not be easy because if I use single quotes to declare a javascript variable, I will have the same problem when the user sends text with single quotes. If I use a regular expression to replace double quotes and do not mark the text as "text | safe", then the other tags will be escaped and the text will be filled with "<br / & gt", etc.

I have an idea that might work, but is ugly and probably not the best option: including the text in the <p class = "hidden"> and then invoking it using jquery.

So the question is, how can I solve this ?, is there a better way? Thanks in advance for your help.

EDIT : I created Runnable to better explain it.

+8
javascript jquery django quotes
source share
2 answers

Use the escapejs filter. Example:

 {{ string|escapejs }} 
+12
source share

Ok, I found a partial solution, hope this helps someone in the future. This is not an elegant solution, so if someone has a better option, he would be welcome.

I have included text that has a "quoted" word inside a hidden html 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 use case for javascript and / or python.

+2
source share

All Articles