Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unterminated string literal for db data in javascript

Tags:

javascript

Here is my code output with passing the data to the console:

console.log('
FUN, FRIENDLY,  * New PRIVATE PARTY ROOM with stage, 70" Satellite TV, comfortable lounge seating
Exciting Bachelor Parties, Unique Surprise Birthday Parties, Divorce, Retirement....You Own IT!
Party includes: 90 Minutes Open Bar, Dedicated Waitress, complimentary Dance of choice for the guest of honor, '.trim());

My result is: SyntaxError: unterminated string literal.

I understand that this is an issue with breaking new lines in javascript and i need to use \ but this is dynamic data as follows:

var b = '<xsl:value-of select="./description"/>'; <--- the output above gets assigned here

So, how do I resolve this issue? The application is not outputting this text on the log. its showing blank Should I Replace \n with \ ?

Not quite sure of the solution.

like image 598
slicks1 Avatar asked Nov 08 '22 16:11

slicks1


1 Answers

The easy solution is just to escape newlines. You want to keep the \n, but only in the string literal form.

Let me give you an example...

You have "\n", which is a literal newline. You want to get "\n", so that the first slash escapes the second.

You can't replace "\" with "\" (or "\" with "\\", to follow correct escaping), because "\n" is only one character.

What you want is simply

yourstring.replace(/\n/g, "\\n");

This performs a RegExp substitution on your string (the first argument is the pattern to look for. I use the "g" flag - global - so that every newline is replaced, not only the first one). The second argument is the replacement - in our case, it's a string literal, but if you needed to generated a value based on your matched pattern, you could use a function.

like image 54
Ven Avatar answered Nov 14 '22 22:11

Ven