The alert() function doesn't render HTML, it is generally accepted that alert()
only renders ASCII strings, and as such line feeds much be defined with \n
(\r\n
would also work)
- For that matter, it is common to format complex
alert()
dialogs using \t
as well.
alert()
passes through directly to the browser, so some browsers will support unicode or extended ASCII character sets. Think about it this way, an alert box is actually a popup dialog from the browser code, not from your page. For this reason the content m,ust conform to the string encoding of that the browser code was written in.
eval()
on the other hand:
eval
The eval() function evaluates JavaScript code represented as a string
This function tries to compile and evaluate a string value as if it was javascript code.
<br/>
is not javascript code and that is why you cannot eval
your string that has <br/>
in it.
<br/>
is the correct mechanism to inject a line break into a paragraph of HTML text.
ASCII /n has not effect on HTML rendering at all because it is classified as a control character that has no visual representation of the character itself. We commonly refer to these characters as whitespace characters.
HTML renders ignore whitespace when rendering, this allows us to add linebreaks in the html code all the time to make it easier to read the code without unnecessarily bloating the page rendering.
This issue between alert()
and html rendering of strings is important to know if you want to build a string once and use it in both locations.
So, if you want to dynamically construct javascript code, and that code contains an alert box AND you want a line break in that alert box, then simply use \n
then if you want to display that constructed code string in html and preserve the line breaks in the html output you can convert all the \n
characters into <br/>
using replace()
:
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>onclick</title>
<script type="text/javascript">
function myNum() {
var result = 0;
var willEval = " ";
willEval += 'var number = 10;';
willEval += '\n';
willEval += '\n alert(number);';
// NOTE: added return statement so we can use the result of the eval
willEval += '\n return number;';
var result = eval('(function(){' + willEval + '})()');
willEval += '\n =' + result;
alert(willEval);
document.getElementById('demo').innerHTML = willEval.replace(/\n/g,'<br />');
}
</script>
</head>
<body>
<h1>onclick</h1>
<button onclick="myNum()">
CLICK ME!
</button>
<p id="demo"></p>
</body>
</html>
These SO posts might be useful
` instead of a `\n` - depending on what exactly you need, if you need to display this as both an alert _and_ inside the page, you would need to handle both differently, if you went with `
` for the HTML part. – CBroe May 08 '20 at 08:50