1
<html>
<script>
function printStringLiteral(theInput) {
    document.body.innerHTML += JSON.stringify(theInput.value)
}
</script>
<body>
<p>Text to modify:<p>
<input type="text" id = "textInput">

<a onclick="printStringLiteral(document.getElementById('textInput'));" href="javascript:void(0);">Get string literal</a>
</body>
</html>

I'm trying to create a simple web page that accepts text as input and returns a string literal, but this web page doesn't display the string literal correctly after it has been generated. I entered <p>"Hi!"</p> as input, but "\"Hi!\" was displayed as output, instead of the correctly formatted string literal. What will I need to do here in order to get the string to display properly?

5
  • What is the result you're expecting? You've converted your string to JSON, hence the escaped quotes, then added it to the document's innerHTML, which will interpret the <p> tags rather than displaying them. I think the browser is doing correctly what you've asked, but not what you expect Commented Aug 1, 2013 at 21:01
  • 2
    Don't JSON.stringify anything that isn't an array or object. The result is just a JSON string (I'm not sure if that result is guaranteed; that's just what V8 seems to return), but not a valid JSON text, so it can be ignored by JSON parsers. Commented Aug 1, 2013 at 21:03
  • -1 for irrelevant whining about downvotes in your question. Commented Aug 1, 2013 at 21:11
  • @Paulpro A string literal is valid JSON. Any implementation abiding to the JavaScript language specification MUST return a valid JSON string as defined in the JSON Spec (At least if it's a valid EcmaScript 5 run time). (It's all in json.org by the way :)). Commented Aug 1, 2013 at 21:18
  • @BenjaminGruenbaum It's a valid JSON string, but not a valid JSON text. I'm not sure about the ECMAScript specification, but to conform to Douglas Crockford's RFC a JSON text much start with [ or {. That's not made very clear on json.org . Commented Aug 1, 2013 at 21:34

1 Answer 1

3

Instead of setting the innerHTML, set the text

function printStringLiteral(theInput) {
    document.body.textContent += JSON.stringify(theInput.value)
}

If you need to support IE8- you need to set innerText too

Sign up to request clarification or add additional context in comments.

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.