After seeing this answer I was trying to find a way to update the contents of a <pre>
tag and have the new-lines displayed using implicit new-lines (i.e. in the string literal). I tried setting various properties: innerHTML, innerText, textContent, nodeValue (after checking answers to this question) yet none seemed to have the white-space preserved.
I am aware I could use String.fromCharCode() - e.g. "Bob " + String.fromCharCode(10, 13) + "is "
... but wanted to find a way using the former syntax as well.
//Perfectly valid code
var foo = "Bob \
is \
cool.";
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('pre').textContent = foo;
});
<pre id="pre"></pre>
Is there a way to update the contents as desired?
答案 0 :(得分:2)
You seem to have misunderstood the answer you linked to. The answer states:
If you wish to have a string which spans multiple lines, you may insert a backslash character '
\
' just before you terminate the line, like so://Perfectly valid code var foo = "Bob \ is \ cool.";
However that string will not contain
\n
characters in the positions where the string was broken into separate lines. The only way to insert a newline into a string is to insert a character with a value of 10, the easiest way of which is the\n
escape character.var foo = "Bob\nis\ncool.";
So this is what you should be doing instead:
//Perfectly valid code
var foo = "Bob\nis\ncool.";
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('pre').textContent = foo;
});
<pre id="pre"></pre>
If you want both to break the string into multiple lines and to have newlines within the string, you need both:
//Perfectly valid code
var foo = "Bob\n\
is\n\
cool.";
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('pre').textContent = foo;
});
<pre id="pre"></pre>
答案 1 :(得分:1)
另一种方法是使用template literals。
public interface IApplicationLogger
{
void LogError(Exception exception);
}
public class ApplicationLogger : IApplicationLogger
{
public void LogError(Exception exception)
{
//do stuff
}
}
public class FooFactory
{
private readonly IApplicationLogger _logger;
public FooFactory(IApplicationLogger logger)
{
_logger = logger;
}
public void CreateFooByUrl(string url)
{
try
{
// business logic
}
catch(Exception exception)
{
_logger.LogError(exception);
}
}
}
//now for the unit test
public void TestCreate()
{
//arrange
var mockLogger = new Mock<IApplicationLogger>(MockBehavior.Strict);
mockLogger.Setup(m => m.LogError(It.IsAny<Exception>()));
var factory = new FooFactory(mockLogger.Object);
//act
factory.CreateFooByUrl("something that will cause exception");
//assert
mockLogger.Verify(m => m.LogError(It.IsAny<Exception>()));
}
// template literal syntax
var foo = `Bob
is
cool.`;
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('pre').textContent = foo;
});