-2

I have a js String with ' or " inside. as a result my code execution stops with: Uncaught SyntaxError: Invalid or unexpected token. Happens in chrome and IE. String example:

XfÍ­Ë`á­²Û)a^ËoT%çíZ
óAuGÒH¾CnäjIònh²~æuÁ8>ÊMï|xWwJ¨L
´³á×ß1Q/;©îé*g®ûA4PÆÎhÂ&V§Fà
#+ûsÙ9
8g¬dJ

fiddle example.

I dont want to change the String in any way like rite-a-string-containing-commas-and-double-quotes.

Itsik Mauyhas
  • 3,824
  • 14
  • 69
  • 114
  • 1
    What is your question? – mrogers Jan 03 '18 at 14:29
  • how to solve `Uncaught SyntaxError: Invalid or unexpected token` is it was not clear. – Itsik Mauyhas Jan 03 '18 at 14:30
  • 1
    it looks like you have multiple lines and you can't have multiple lines in a JS string like that. – Daniel A. White Jan 03 '18 at 14:35
  • Without altering your string, there are exactly 3 ways to create strings in JavaScript: `\``, `'` and `"`. Last two wont work because the string is multiline, and the first one won't work because the symbol is inside the string and you do not want to escape it. You could alternatively read the string from some file. – NikxDa Jan 03 '18 at 14:37
  • @DanielA.White - and remove `enter` or `\n` in the backend will do the trick? – Itsik Mauyhas Jan 03 '18 at 14:39
  • 1
    Where is your string? Directly in your JS source code? Or are you sending it from a script (say, PHP)? If the former, you can just escape the offending characters (you'll also have to replace the newlines). Be aware that you may end up with encoding issues for what looks like binary code if you haven't kept a consistent encoding/charset while manipulating it. – jcaron Jan 03 '18 at 14:39
  • you might be able to use a JSON encoder that will handle all the special cases. – Daniel A. White Jan 03 '18 at 14:46

2 Answers2

1

If the line breaks are part of your string value, you need to use \n. In .js file, you can't treat .js like a regular 'text editor' with that 'visual' representation.

var t = "\nXfšÍ‰­Ë`á­²Û)a^ËoT‹%Ž‘çíZ\nóAuG҇H¾CnäjIònh²~æuÁ8>ÊMï|xWwJ¨L\n´³á×ß1Q/;‘©îé*g®ûA4PƊÎh‰Â&V§Fà\n#+û‚sÙ9\n8g¬dJ"

console.log( t );

Hope it helps!

zack
  • 11
  • 2
1

You can use ES6 String Template

let data = `#+ûsÙ9'"`
console.log(data) // #+ûsÙ9'"
ventaquil
  • 2,780
  • 3
  • 23
  • 48