我正在尝试在javascript中创建一个正则表达式。我想做什么:
class=“get-me”
的html元素。I found you
替换它。示例:
<div class="get-me" />
结果:I found you
<div>Some text <div class="get-me" data-type="data-type" js="js" /> more things happening here</div>
结果:<div>Some text I found you more things happening here</div>
<div>Some text <p class="get-me" /> more things</div>
结果:<div>Some text I found you more things</div>
I m testing <<<<div class="get-me" />
结果:I m testing <<<I found you
感谢。
答案 0 :(得分:1)
这样可以找到包含 class="getMe"
的所有标记
然后,您可以将其替换为任何内容(从文本中删除)。
请注意,如果不匹配所有代码,您就无法匹配特定代码 这是因为标记可以嵌入其他标记等...
/<[\w:]+(?=(?:[^>"']|"[^"]*"|'[^']*')*?\sclass\s*=\s*(?:(['"])\s*getMe\s*\1))\s+(?:"[\S\s]*?"|'[\S\s]*?'|[^>]*?)+>/
https://regex101.com/r/PHUrIi/1
扩展
< [\w:]+ # Any tag
(?= # Assert (a pseudo atomic group)
(?: [^>"'] | " [^"]* " | ' [^']* ' )*?
\s class \s* = \s*
(?:
( ['"] ) # (1), Quote
\s* getMe \s* # With 'class="getMe"
\1
)
)
\s+
(?: " [\S\s]*? " | ' [\S\s]*? ' | [^>]*? )+
>
答案 1 :(得分:1)
如果没有进入解析HTML辩论,这将回答您原来的(未经编辑的)问题:
const replacementText = 'I found you';
const regex = /(.*)<\w+\s.*class="get-me".*\/>(.*)/;
let str = '<div>Some text <div class="get-me" data-type="data-type" js="js" /> more things happening here</div>';
str = str.replace(regex, `$1${replacementText}$2`);
输出
"<div>Some text I found you more things happening here</div>"
这是给你的JSBin:https://jsbin.com/rowaxayodu/edit?js,console