TheNeosrb TheNeosrb - 3 months ago 19
HTML Question

dynamically add backslash to end of string line

I have code that gets some text from database and inserts it inside

javascript var
. This is the code:

<script>
var = <?php echo $var ?>
</script>


When the page is loaded,
var
looks like this:

<script>
var = "This is first line
This is second
This is third..."
</script>


Is there a way to dynamically add a backslash after each line?

EDIT :

I am using
PHP
to echo the text and I want to manipulate it inside
javascript

Answer

Just split the variable into new lines with whatever delimiter you like:

<?php
$var = "This is line 1|##|This is line 2|##|This is line 3";
?>
<script type='text/javascript'>
var lines = "<?=$var?>";
var res = lines.split("|##|");

res.forEach(function(entry) {
    alert(entry + "\\");
});
</script>
Comments