我想要将一个单词截断为50个字符,但在50个字符中,它不应该是一个HTML标签.假设我有以下的HTML:

<p>This is a test message</p>This is a test message<p>This is a test <a href="#">message</a> </p>

然后它应该计算50个字符,只包括"这是一条测试消息这是一条测试消息"

截断后,它应该显示如下:

<p>This is a test message</p>This is a test message<p>This</p>

我希望使用jQuery来实现这一点.

100: 抱歉,再加一个条件:

我想显示到最后一个点,但不能超过50个字符,如下所示:

<p>This is a test message</p>This is a test message.<p>This is a test <a href="#">message.</a> </p>

则输出将为

<p>This is a test message</p>This is a test message.

推荐答案

我认为您不需要为此使用jQuery.一个快速的解决方案是循环遍历每个字符.如果字符在<>个字符以内,则将其添加到最终字符串.否则,仅当已添加的<>以外的字符计数小于50时才添加它:

function shorten(s, maxChars) {
  let short = '';
  let tagFlag = false;
  let i = 0;
  for (const ch of s) {
    if (ch == '>' || ch == '<') {
      tagFlag = !tagFlag;
      short += ch;
    } else if (tagFlag) {
      short += ch;
    } else if (i < maxChars) {
      short += ch;
      i++;
    }
  }
  return short;
}

console.log(shorten('<p>This is a test message</p>This is a test message<p>This is a test <a href="#">message</a> </p>', 50));

唯一的缺陷是,像<a>这样的标签仍然包括在内,然而,它们是空的.因为额外的标签是空的,所以它们不会出现,这应该不会有什么不同.

根据您的更新,您可以将文本保存在一个临时变量中,直到到达一个点,然后只在到达点时才完全添加该文本.这将抛出最后一个圆点之后的任何额外文本.然后,判断抛出的内容,并只添加回标记,以确保结果不会遗漏任何结束标记.展开下面的代码片段可以看到这一点.

function shorten(s, maxChars) {
  let short = '';
  let temp = '';
  let tagFlag = false;
  let i = 0;
  for (const ch of s) {
    if (ch == '>' || ch == '<') {
      tagFlag = !tagFlag;
      temp += ch;
    } else if (ch == '.' && i < maxChars) {
      short += temp + '.';
      temp = '';
    } else if (tagFlag) {
      temp += ch;
    } else if (i < maxChars) {
      temp += ch;
      i++;
    }
  }
  
  tagFlag = false;
  for (const ch of temp) {
    if (ch == '>' || ch == '<') {
      tagFlag = !tagFlag;
      short += ch;
    } else if (tagFlag) {
      short += ch;
    }
  }
  return short;
}

console.log(shorten('<p>This is a test message</p><p>This is a test message.<p>This is a test <a href="#">message.</a> </p></p>', 50));

Javascript相关问答推荐

如何使用JavaScript用等效的功能性HTML替换标记URL格式?

如何避免移动设备中出现虚假调整大小事件?

MongoDB中的引用

Redux查询多个数据库Api reducerPath&

在vercel throws上部署带有gunjs的sveltekit应用无法找到模块./' lib/文本编码'

从Node JS将对象数组中的数据插入Postgres表

引用在HTMLAttributes<;HTMLDivElement>;中不可用

如何将Openjphjs与next.js一起使用?

我在Django中的视图中遇到多值键错误

如何迭代叔父元素的子HTML元素

覆盖TypeScrip中的Lit-Element子类的属性类型

在HTML语言中调用外部JavaScript文件中的函数

TypeError:无法分解';React2.useContext(...)';的属性';basename';,因为它为空

从Nextjs中的 Select 项收集值,但当单击以处理时,未发生任何情况

在使用REACT更改了CSS类之后,无法更改CSS样式

使用NextJS+MongoDB+Prisma ORM获取无效请求正文,无法发布错误

如何在Press上重新启动EXPO-AV视频?

在Vercel中部署Next.js项目时获取`ReferenceError:未定义文档`

在查看网页时,如何使HTML中的按钮工作方式类似于鼠标上的滚轮或箭头键?

Jexl to LowerCase()和Replace()