从函数输入到Javascript插入带换行符的单词

I have a condition below. pop function in button input has line 1 followed by newline Line2. When I click on button to javascript it pops error " Unexpected token ILLEGAL " in Console.

Value inside pop() of button is generated dynamically. I get this error only if I have a new line char in the input text.

<script type='text/javascript'>

function pop(valu)
{
alert("here"+valu);
document.getElementById('box').innnerHTML = valu;
}

</script>

<button onclick="pop('Line 1
Line 2')"> Click </button>
<textarea id='box'></textarea>

Backend is PHP.

Is there any way to achieve this on foreground ? or should I make any changes of inserting values to DB ?

I directly store the values in DB with newline character.

Solution is use to nl2br function in PHP side

nl2br($yournewlinestring); 

function of PHP to convert newline to enter a new line for

But before storing convert your html line breaks in php like this

$_POST['xyz'] = preg_replace('/(?:
|[
])/', PHP_EOL, $_POST['xyz'] ); 

If you want the newline characters, just do something like:

<?php $pop_variable = str_replace("
", '
', $pop_variable); ?>
<button onclick='pop("<?php echo htmlentities($pop_variable, ENT_QUOTES) ?>")' />

Remember to also run htmlentities to escape the quotes.

I do think this is doing too much in HTML, though. It might be more beneficial to store this in a PHP array and then json_encode() it. That way you don't have to do the above or take into account what happens when a " or ' is in the $pop_variable and might also be expandable if you wanted to add more buttons (of course, this depends on your use case).

Example:

<script>
function pop(valu) {
    // Should do some error checking to ensure pop_var is set
    document.getElementById('box').innnerHTML = pop_var[valu];
}
var pop_var = <?php echo json_encode(['button1' => "Line 1
Line2", 'button1' => "Another Line 1
Another line with ' single quotes..."]);
</script>

<button onclick="pop('button1')">Click</button>
<button onclick="pop('button2')">Click</button>
<textarea id='box'></textarea>