JavaScript-计算div中的字符数,并跳过其中的标记



目的是在<p/>文本的55个字符后添加三个点。<p>内部可能有更多的标签,如<b/><i/><a/>等,这些标签在计数时需要跳过。计数完成后,我希望将计数的文本与其原始标记一起分配,请参阅下面所需的输出。

例如

<p><i>Every story has a beginning.</i> Discover how <b>company</b> began in 1996 and grew into a global design house at the forefront of <i>innovative</i> material design and expert <a href="https://www.google.com" target="_blank">craftsmanship</a>.</p>

期望输出:

<p><i>Every story has a beginning.</i> Discover how <b>company began</b>...</p>

我使用的是纯JavaScript(没有jQuery(!谢谢你的帮助。

我想我已经找到了一些可能会有所帮助的方法。它不再指望"<"并在'>'上再次开始,因此忽略标记,只计算包含的字符。它还跟踪每个打开的标签,并在标签关闭时将其删除,因此最后它会关闭所有保持打开的标签。。。

const cutString = (str) => {
let stringCount = 0
let keepCounting = true
let ans = ''
let openTags = []
for (let i = 0; i<str.length; i++){
if (str[i] == "<") {
keepCounting = false
if (str[i+1] != `/`) openTags.push(str[i+1])
continue
}
if (str[i] == ">") {
keepCounting = true
if (str[i-2] == `/`) openTags.splice(openTags.indexOf(str[i-2]), 1)
continue
}
if (keepCounting) stringCount++
if (stringCount == 56) {
ans = str.slice(0, i)
break
}
}
openTags.forEach(tag => ans = ans+`</${tag}>`)


return ans + "..."
}
let testString = `<p><i>Every story has a beginning.</i> Discover how <b>company</b> began in 1996 and grew into a global design house at the forefront of <i>innovative</i> material design and expert <a href="https://www.google.com" target="_blank">craftsmanship</a>.</p>`

console.log(cutString(testString))

输出:

"<p><i>Every story has a beginning.</i> Discover how <b>company</b> began</p>..."

最新更新