我說,當我使用反引號警報消息不正確顯示:如何在使用反引號時正確顯示JavaScript警報內的文本?
例子:
var classicMsg = "Lorem Ipsum is simply dummy text of the printing and typesetting "
\t \t \t + "ndustry. Lorem Ipsum has been the industry's standard dummy "
\t \t \t + "text ever since the 1500s, when an unknown printer took a galley "
\t \t \t + "of type and scrambled it to make a type specimen book.";
var backticksMsg = `Lorem Ipsum is simply dummy text of the printing and typesetting
ndustry. Lorem Ipsum has been the industry's standard dummy
text ever since the 1500s, when an unknown printer took a galley
of type and scrambled it to make a type specimen book.`;
document.getElementById("btnAlert1").addEventListener('click', function(){
alert(classicMsg);
});
document.getElementById("btnAlert2").addEventListener('click', function(){
\t alert(backticksMsg);
});
li{cursor: pointer;}
<ul>
<li id="btnAlert1">Test with classic message</li>
<li id="btnAlert2">Test with backticks message</li>
</ul>
是否有更好的方法來正確顯示警報反引號文字比寫一個自定義函數來做到這一點?...我的意思是沒有做這樣的事情:
function formatTextBeforeCallingAlert(txt) {
return txt.replace(/\n/g, '').replace(/\t/g, '');
}
「插入源的任何新行字符是模板文字的一部分」。 - [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) - 所以除非你想換行,否則不要添加換行符。 – Gerrit0
@ gerrit0但我不想失去使用「插值」插入變量內容的優勢... –
爲什麼刪除新行會阻止插值? – charlietfl