javascript - 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>..."
推荐阅读
- ejabberd - ejabberd MUC-Sub 麻烦
- android - 本地类的 Proguard 规则
- java - JcaPEMWriter 可以生成 PKCS#8 输出吗?
- php - 当应用程序在本地运行时如何修复 PHP 上的重定向错误
- php - Google Api,如何将 access_token 传递给 API 调用
- javascript - 在反应中选择带有jquery的当前元素
- angularjs - 使用绑定指令不起作用的两种方式编辑对象属性
- apache-spark - 结构化流式传输作业突然停止
- google-apps-script - 删除原始数据时,如何在不删除复制数据的情况下将数据从 Google Sheet1 移动或复制到 Sheet2
- amazon-web-services - s3-select查询字段名数据