【问题标题】:How can I exclude a class inside a regex string?如何排除正则表达式字符串中的类?
【发布时间】:2020-03-21 10:04:08
【问题描述】:

我目前正在尝试构建一个正则表达式,它替换字符串中的所有 HTML 标记,不包括特殊元素。问题是我发现没有办法排除特殊元素的结束标记。这是我的代码:

let str = 'You have to pay <div class="keep-this">$200</div> per <span class="date">month</span> for your <span class="vehicle">car</span> <div class="keep-this">$500</div> also';

console.log(str.replace(/(?!<div class="keep-this">)(<\/?[^>]+(>|$))/g, ""));

我该如何解决这个问题?

【问题讨论】:

  • 是否可以选择使用正则表达式以外的其他东西?
  • 是的,主要是目的达到了

标签: javascript regex


【解决方案1】:

试试这个选项,它匹配所有 HTML 标记,不包括那些具有属性 class="keep-this" 的标记。

let str = 'You have to pay <input class="some-class"/> blah <div class="keep-this">$200</div> per <span class="date">month</span> for your <span class="vehicle">car</span> <div class="keep-this">$500</div> also';

console.log(str.replace(/<\s*([^\s>]+)(?:(?!\bclass="keep-this")[^>])*>(.*?)(?:<\/\1>)|<\s*([^\s>]+)(?:(?!\bclass="keep-this")[^>])*\/>/g, "$2"));

下面是正则表达式模式的解释:

<                                 match < of an opening tag
\s*                               optional whitespace
([^\s>]+)                         match and capture the HTML tag name in $1 (\1)
(?:(?!\bclass="keep-this")[^>])*  match remainder of tag,
                                  so long as class="keep-this" is not seen
>                                 match > of an opening tag
(.*?)                             match and capture the tag's content in $2,
                                  until hitting the nearest
(?:<\/\1>)                        closing tag, which matches the opening one
|                                 OR
<\s*([^\s>]+)                     match a standalone tag e.g. <input/>
(?:(?!\bclass="keep-this")[^>])*  without a closing tag
\/>                               which matches                            

然后,我们只需将所有此类匹配项替换为空字符串,即可有效地删除它们。

【讨论】:

  • 不错!不过,解释的第 4 行缺少右括号。
  • 否...检查第 6 行...右括号在那里
  • 啊,我的意思是),而不是&gt;。它不见了,对吧?
  • 你应该添加s标志,以防要删除的标签跨越多行。或者使用[\s\S]而不是.
  • @Mr.Jo 对不起,我想我错过了这个要求。我的答案只需要稍作改动。
【解决方案2】:

如果您想删除所有不属于keep-this 类的html 元素,您也可以使用DOMParser,例如使用:not

let str = 'You have to pay <div class="keep-this">$200</div> per <span class="date">month</span> for your <span class="vehicle">car</span> <div class="keep-this">$500</div> also';
let parser = new DOMParser();
let doc = parser.parseFromString(str, "text/html");
doc.querySelectorAll("body *:not(.keep-this)").forEach(e => e.replaceWith(e.innerHTML));
console.log(doc.body.innerHTML);

【讨论】:

  • 这里删除了monthcar这个词。
  • @Mr.Jo 啊,我明白了 :) 我删除了该元素。我已经更新了它,用 innerHTML 替换它。
猜你喜欢
  • 1970-01-01
  • 2017-04-13
  • 2012-02-17
  • 1970-01-01
  • 2021-12-08
  • 1970-01-01
  • 2020-04-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多