简体   繁体   中英

how to give a line break with the javascript string without breaking javascript code?

I need to add a break in the javascript with the below situation.

<?php
$str_alert = "";
if(isset($case1)){
    $str_alert .= "have case1 \n";
}
if(isset($case2)){
    $str_alert .= "have case2 \n";
}
if(isset($case3)){
    $str_alert .= "have case3 \n";
}
if(!empty($str_alert)){
?>
<script type="text/javascript" >
$(document).ready(function(){
     alert("<?=$str_alert?>");
});
</script>

it break the javascript code and shows the error

SyntaxError: unterminated string literal

please give me any solution

Add \\ to escape \\n in php. Try following code

<?php
$str_alert = "";
if(isset($case1)){
    $str_alert .= "have case1 \\n";
}
if(isset($case2)){
    $str_alert .= "have case2 \\n";
}
if(isset($case3)){
    $str_alert .= "have case3 \\n";
}
if(!empty($str_alert)){
?>
<script type="text/javascript" >
$(document).ready(function(){
     alert("<?=$str_alert?>");
});
</script>

You need to represent characters that are not allowed as literals in JS strings (like new lines) by escape characters.

Since JSON is a data format based on a subject of JavaScript's literal syntax, you can use PHP's json_encode function to convert any basic data type (string, number, array, associative array) into JavaScript code with all the correct escape characters.

By default it will even escape / so you can safely output the string </script> .

alert(<?=json_encode($str_alert);?>);

Since the " will be included in the JSON, you should not add them manually.

Javascript strings can't break across newlines without an escape (). See this question for detailed answers:

How do I break a string across more than one line of code in JavaScript?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM