Initialized string literal for db data in javascript

Here is my code output with data transfer 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: SyntaxError: unterminated string literal .

I understand that this is a problem with breaking newlines 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 solve this problem? The application does not log this text. its display is empty Should I replace \n with \ ?

Not quite sure about the solution.

+5
source share
2 answers

A simple solution is to simply exit the new line. You want to save \n , but only in string literature.

Let me give you an example ...

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

You cannot replace "\" with "\" (or "\" with "\\" to follow proper escaping) because "\ n" is just one character.

You just want

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

This does the RegExp lookup in your line (the first argument is the search pattern. I use the "g" flag - global - so that every new line is replaced not only by the first). The second argument is replacement — in our case, it is a string literal, but if you need to create a value based on your mapped template, you can use the function.

+1
source

You can replace \n with \\\n . The first two \ will cause one backslash to be part of the output. \n at the end will break the line.

The output of your code will look like this:

 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()); 

If you need to use the actual line breaks in the application, replace \n with \\n . The output will be

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

Source: https://habr.com/ru/post/1247653/


All Articles