How to Handle Newlines in JavaScript? (From PHP)

How to handle newlines in Javascript? (from PHP)

$txt = str_replace( array( "\n", "\r" ), array( "\\n", "\\r" ), $txt );

should replace newlines. Don't do it this way.

This is a naïve implementation of string escaping for JavaScript. As you're actually trying to format a string for use in JavaScript, a much better solution would be to use json_encode:

$txt = json_encode($txt);
echo "<script>var out={$txt};</script>";

json_encode will correctly escape special characters in strings, such as quotes, tabs, form feeds, and other special unicode characters. It will also perform all the correct escaping for converting objects, arrays, numbers, and booleans.

using php string with line breaks as javascript variable

This has already been answered here https://stackoverflow.com/a/4270709/3004335

However, you can use json_encode

<script type="application/javascript">
$(document).ready(function () {
document.getElementById('job_type').value = "<?php echo set_value('job_type') ?>";
document.getElementById('job_cat').value = "<?php echo set_value('job_cat') ?>";

if("<?php if(validation_errors() == false) echo "false"; else echo "true"; ?>"=="false")
{
$('#job_title').val(<?php echo json_encode($job[0]->job_title); ?>);
$('#job_type').val(<?php echo json_encode($job[0]->job_type); ?>);
$('#job_cat').val(<?php echo json_encode($job[0]->job_cat); ?>);
$('#salary').val(<?php echo json_encode($job[0]->salery); ?>);
$('#job_descp').text(<?php echo json_encode($job[0]->job_desc); ?>);//error here
}
});
});
</script>

You do however need to be careful about cross site scripting

See here https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet in particular rule #0

encoding a PHP variable with quotes and line breaks to be passed to a Javascript function (and then reverse the encoding)

I ran into problems using some of the answers proposed here, including issues with line breaks and decoding certain html entitites like /. I ended up using rawurlencode (in PHP) and decodeURIComponent (in Javascript) as matching functions to encode/decode the string so it could be passed as a JS variable. Here is working code for anybody else running into this problem.

<?php
$str =<<<EOT
Tromp L'oeil Sheath Dress

You will certainly "trick the eye" of many in this gorgeous illusion. Add it to your fall wardrobe before it disappears.
Available in Black/Nude
EOT;
echo 'here is the string: <pre>' . $str . '</pre>';
?>
<p>below is the variable doc.write'd after being rawurlencod'ed in PHP then decodeURIComponent'ed in JS:</p>
<script type="text/javascript">
<?php
echo 'document.write(decodeURIComponent("'. rawurlencode($str).'"));';
?>

Pass a PHP string to a JavaScript variable (and escape newlines)

Expanding on someone else's answer:

<script>
var myvar = <?php echo json_encode($myVarValue); ?>;
</script>

Using json_encode() requires:

  • PHP 5.2.0 or greater
  • $myVarValue encoded as UTF-8 (or US-ASCII, of course)

Since UTF-8 supports full Unicode, it should be safe to convert on the fly.

Note that because json_encode escapes forward slashes, even a string that contains </script> will be escaped safely for printing with a script block.

adding line break into javascript from php

Got it at last, after too many days headache!

I was looking at the wrong replacement theories

The answer is to use the following line:

$main_article1 = preg_replace("/\r\n|\r|\n/",'<br/>',$row[main_article]);

Now it works perfectly.

Thanks to all for your help.

Regards

Tog

How to trim unwanted newlines/linebreaks from PHP variable?

document.getElementById('1_1_50').value =
'<?php echo str_replace("\n", "\\n", $edu_notes) ?>';

Display PHP string with quotes and newline in Javascript (alert)

Use json_encode to create a valid JS string:

<script>
alert(<?php echo json_encode($this->info); ?>);
</script>

Javascript inserttext with newline

(Posted answer on behalf of the question author).

str_replace(PHP_EOL, '[br]',($_POST['replytext']))

This did the job. onClick function doesn't allow <br /> or any kind of new line.

How to preserve newlines in a textarea when passing by POST?

I see that the purpose of your javascript code is only to fill in any input values. This can be done by utilizing <form> directly. Most likely, copying your data into a <input tye="text"> (text is the default type) will mangle your newlines.

Something like this should be equivalent and without the presented issue:

<!DOCTYPE html>
<html>
<head>
<title>File Editor</title>
<meta charset="UTF-8"/>
<style>h1{text-align:center;font-size:40px;padding:10px;border:2px solid black;border-radius:10px;}textarea{width:90%;height:90%}</style>
</head>
<body>
<h1>File Editor</h1>
<?php
if(isset($_POST["save"],$_POST["extra"]))
file_put_contents($_POST["filename"],$_POST["extra"]);
if(isset($_POST["delete"]))
unlink($_POST["filename"]);
if(!isset($_POST["filename"],$_POST["submit"])){
?>
<form action="editor.php" method="post">
<label for="filename" id="n">Enter a file to edit: </label>
<input type="text" name="filename" placeholder="Enter file name to edit"/>
<button type="submit" name="submit">Submit</button>
</form>
<?php }else{ ?>
<span style="display:none"><?php echo $_POST["filename"]; ?></span>
<form action="editor.php" method="post">
<textarea name="extra"><?php echo htmlspecialchars(file_get_contents($_POST["filename"])); ?></textarea>
<br/>
<input type="hidden" name="filename" value="<?= $_POST['filename'] ?>">
<button name="save">Save</button>
<button name="close">Close file</button>
<button name="delete" style="color:red">Delete file</button>
</form>
<script>
document.getElementById("delete").onclick=function(e){
if(!confirm("Are you sure you want to delete this file?")) e.preventDefault();
}
</script>
<br/><br/>
<?php } ?>
</body>
</html>

Also as mentioned, you will probably need to format the newlines for html when displaying.


When needing to pass the same or hidden data you can use <input type="hidden" name=".." value="..">. This is used to pass the filename. The desired action is passed with the button press. The name of button you press will be passed in the request.

PHP - how to create a newline character?

Only double quoted strings interpret the escape sequences \r and \n as '0x0D' and '0x0A' respectively, so you want:

"\r\n"

Single quoted strings, on the other hand, only know the escape sequences \\ and \'.

So unless you concatenate the single quoted string with a line break generated elsewhere (e. g., using double quoted string "\r\n" or using chr function chr(0x0D).chr(0x0A)), the only other way to have a line break within a single quoted string is to literally type it with your editor:

$s = 'some text before the line break
some text after';

Make sure to check your editor for its line break settings if you require some specific character sequence (\r\n for example).



Related Topics



Leave a reply



Submit