我尝试使用 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/