首页 > 解决方案 > 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)!谢谢你的帮助。

标签: javascript

解决方案


我想我已经想出了一些可能会有所帮助的东西。它停止计数'<'并重新开始'>',因此忽略标签并且只计算封闭的字符。它还跟踪每个打开的标签并在标签关闭时将其删除,因此最后它会关闭所有保持打开的标签...

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>..."

推荐阅读