javascript - 正则表达式执行后返回null?

标签 javascript html regex

我尝试使用 RegExr 删除按钮周围的包装,但它返回空值。

我使用了this的解决方案问题,像这样:

var title = $( ".redButton" ).text();
var myString = $( "#content" ).html();
var myRegexp = /(<p>\s<button class"redButton">)((?:\s|.{1,50})*)(<.button>\s<.p>)/g;
var match = myRegexp.exec(myString);

console.log(match);

所以我最终可以改变这个:

<article id="content">
    <p>
        <button class="redButton">EEN HELE LANG TITEL IN EEN KNOP</button>
    </p>
</article>

进入此:

<article id="content">
        <button class="redButton">LONG TITLE IN A BUTTON</button>
</article>

在继续之前,我想检查一下正则表达式是否有效,但显然没有。 This解决方案可以使用转义来解决问题,但我不明白什么时候应该转义,什么时候不应该转义。

有人可以帮忙吗?

最佳答案

正则表达式和 HTML 通常不能很好地协同工作。为什么不使用 DOMParser 来代替呢?将字符串解析为文档,将 button 附加到 article,然后删除 p:

const htmlStr = `<article id="content">
    <p>
        <button class="redButton">EEN HELE LANG TITEL IN EEN KNOP</button>
    </p>
</article>`;
const doc = new DOMParser().parseFromString(htmlStr, 'text/html');
const button = doc.querySelector('.redButton');
const parentToRemove = button.parentElement;
const ancestorToAppendTo = parentToRemove.parentElement;
ancestorToAppendTo.appendChild(button);
parentToRemove.remove();
console.log(doc.body.innerHTML);

这会将按钮附加到其父级的父级,并从 HTML 中删除其父级

关于javascript - 正则表达式执行后返回null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52964745/

相关文章:

javascript - 如何使用 Dojo Store 进行客户端数据缓存?

html - 制作一个可编辑的下拉框

Javascript:从字符串中提取日期?

javascript - 如果数组中的项目与另一个数组中的项目一致,则替换它们

javascript - React 如何从 json 数据以表单形式呈现嵌套下拉列表?

php - 在 MySQL+PHP 中过滤数据库表的搜索以获得每次搜索最接近的结果

html - 在包含许多元素的列表菜单中突出显示单个元素

php - Preg_replace 价格字符串 (PHP)

mysql - 数据库值中的单引号会破坏导入

javascript - 将 item-left-edit 更改为 item-right-edit 为 Ionic