gpt4 book ai didi

javascript - textContent() 格式化文本中没有空格

转载 作者:行者123 更新时间:2023-12-05 01:29:05 26 4
gpt4 key购买 nike

我有一个这样的html:

<div id="info">
<h1> My title </h1?
<div>
<p> Here is a text and one paragraph </p>
<p> Another paragraph </p>
</div>
</div>

我想从整个 div#info 中获取没有标签的内部文本。所以我用这个:
document.querySelector('div#info').textContent

结果有一些这样的空格:
"
My title




Here is a text and one paragraph
Another Paragraph




"

任何想法是否有任何命令可以将结果提供给这样的一行:
 "My title Here is a text and one paragraph Another Paragraph"

我也尝试了 innerText()但它又有空格。

最佳答案

您需要一个正则表达式来删除所有换行符和多余的空格:

.replace(/[\n\r]+|[\s]{2,}/g, ' ')

那么你可以 .trim()该调用的结果:

console.log(
document.querySelector('div#info')
.textContent
.replace(/[\n\r]+|[\s]{2,}/g, ' ').trim()
)
<div id="info">
<h1> My title </h1>
<div>
<p> Here is a text and one paragraph </p>
<p> Another paragraph </p>
</div>
</div>

关于javascript - textContent() 格式化文本中没有空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42920985/

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