Javascript的正则表达式:替换字符串中的实例
问题描述:
我想在JavaScript中创建一个正则表达式。我想要做的:Javascript的正则表达式:替换字符串中的实例
- 我想看看是否有一个html元素
class=“get-me”
字符串中的任何地方。 - 如果有我想用
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 <p class="get-me" /> more things</div>
I m testing <<<<div class="get-me" />
结果:<div>Some text I found you more things happening here</div>
结果:<div>Some text I found you more things</div>
结果:I m testing <<<I found you
谢谢。
答
没有进入解析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>"
答
这个工程,发现任何标签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]*? ' | [^>]*?)+
>
[不解析与正则表达式HTML](https://stackoverflow.com/a/1732454/3001761) – jonrsharpe
为什么你认为我想解析HTML?我有一个不解析的特定用例。 – zsid
在html标签中查找一个类是_parsing_。为此,您可以使用[sizzlejs](// sizzlejs.com)等库,而不是使用正则表达式。也没有JavaScript的后代,但[有替代品](https://stackoverflow.com/q/7376238/6320039) –