使用脚本查找文本字符串,直到第一个html标记

Using script to find string of text up until first html tag

本文关键字:第一个 html 标记 字符串 脚本 查找 文本      更新时间:2023-09-26

我有一个返回消息的服务。该消息可以是纯文本或html格式文本的组合。

ex1: "This is a message"
ex2: "<p> This is also a message <p/>"
ex3: "This is also a <strong> message </strong>"

我们想要做的是编写一个脚本,它将返回到第一个标记之前尽可能多的纯文本。在上面的例子中:

  1. 将返回"This is a message.
  2. 将返回"
  3. 将返回"This is also a"

我不确定什么方法是最好的。我可以用Regex或JS来完成这个吗?我知道Regex可以很容易地返回两个标签之间的文本,但我正在寻找的是有点不同。谢谢你的建议和帮助。

最简单的解决方案是匹配除< s以外的任何内容,从字符串的开头开始:

match = subject.match(/^[^<]*/)[0];

如果< s可能出现在第一个HTML标记之前的注释/引号字符串中,则会失败,但这可能不是问题。

测试JSFiddle

解释:

^      # Anchor the match to the start of the string.
[^<]   # Match any character that's not a <
*      # zero or more times (as many as possible).