0

What I am doing:

I am storing (MySQL) formatted text that is structured like this:

I'm Robert (I'm = I am)<br>You're in France (You're = You are)<br><br><strong></strong><span class="st">?</span> <b>I</b>'m Robert  <br>? Am Robert <del> <br></del><br>? <b>You</b>'re Robert <br>? Are Robert  <br><br>I'm = I am<br>You're = ___ ___?<br><br><br><br>

I am trying to retrieve this string from the database an then append it into a WYSIWYG editor like this.

function enableEditMode(){
            card_content.document.designMode = 'On';
            $('iframe[name=card_content]').contents().find('body').append("I'm Robert (I'm = I am)<br>You're in France (You're = You are)<br><br><strong></strong><span class="st">?</span> <b>I</b>'m Robert  <br>? Am Robert <del> <br></del><br>? <b>You</b>'re Robert <br>? Are Robert  <br><br>I'm = I am<br>You're = ___ ___?<br><br><br><br>");
}

I get the following error:

SyntaxError: missing ) after argument list

I assume this is because of the "" quotes causing issues.

Question:

How do I go about appending HTML into the DOM without encuring syntax errors like this?

6
  • Classic quotes issue Commented Apr 10, 2017 at 12:52
  • Is there a function to excape quotes? e.g. \"foo\"? Commented Apr 10, 2017 at 12:53
  • 1
    You need to replace " in the string with \" so that its escaped. Exactly how you do that will depend on the server language you're using to get data from your SQL database Commented Apr 10, 2017 at 12:53
  • 1
    you should use &quot; Commented Apr 10, 2017 at 12:54
  • 1
    @REDEVI_ that won't work in this case as the quotes are within an attribute, not part of the HTML content. Commented Apr 10, 2017 at 12:56

2 Answers 2

1

I think you need to escape single quote or double quotes:

function addslashes( str ) {
    return (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}

from: Escaping Strings in JavaScript

Or you escape the string in server side and return the escaped string. Therefore, the result should be like this:

"this is a test, isn\'t it great! <span class=\"test\">Test</span>"
Sign up to request clarification or add additional context in comments.

1 Comment

Cool, serverside worked for me... I was using PHP so I just wrapped my HTML in addslashes(). Thanks!
1

Just replace

class="st"

by

class='st'

should do the trick. I dont see more quote conflicts.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.