gpt4 book ai didi

javascript - 从模板字符串中渲染空白

转载 作者:行者123 更新时间:2023-11-30 19:38:55 26 4
gpt4 key购买 nike

如果我有一个带空格的模板字符串,比如

(`${firstName},

Thanks for ordering ${product1}.

Your order has shipped.`);

如何将其呈现为 html,包括空格?

我试过使用 innerHTML,但结果是

Hello Somebody, Thanks for ordering something. Your order has shipped.
<html>
<head>
<meta name="viewport" content="minimum-scale=1.0, width=device-width, maximum-scale=1.0, user-scalable=no"/>
<meta charset="utf-8">

<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</head>
<body>

<div id="test"></div>
<script type="text/babel">

var firstName = "Somebody"
var product = "something"


const element = (`
Hello ${firstName},

Thanks for ordering ${product}.

Your order has shipped.
`);

document.getElementById('test').innerHTML = element;

</script>
</body>
</html>```

Expected:

Hello Somebody,

Thanks for ordering something.

Your order has shipped.


Actual results:

Hello Somebody, Thanks for ordering something. Your order has shipped.

最佳答案

HTML 默认会折叠空格。您可以使用 css white-space: pre 保留空格或者用 <br> 替换换行符将呈现换行符的标记,如下所示:

document.getElementById('test').innerHTML = element.replace(/\n/g, '<br>')

关于javascript - 从模板字符串中渲染空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55623601/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com