gpt4 book ai didi

javascript - Javascript 的正则表达式

转载 作者:行者123 更新时间:2023-11-29 20:54:07 26 4
gpt4 key购买 nike

我正在尝试清理 Angular 代码以便稍后将其发送到 jsPDF。当发现无法识别的 HTML 代码时,jsPDF 通常会失败,所以我试图摆脱它。

到目前为止,表达式应该是这样的

'<code>'.replace(/ng-\w+="(\w|\d\s)+"/,'')

这对于简单的事情很有用,但我需要更详细的表达式,但我没能遇到它。

ng-\w+=" 
#Finds expressions like ng-if, ng-model, ng-class, etc

(\w|\d\s)+
#This expressions only accepts spaces, numbers and digits

我真正需要的是获取双引号之间的所有内容

最佳答案

为什么不像这样使用 DOMParser 呢?最好不要尝试用正则表达式解析 HTML

const html = `
<div id="myid" class="myclass" ng-if="ngif attribute" ng-model="ngmodel attribute" ng-class="ngclass attribute">content</div>
<div ng-if="another ngif attribute">content 2</div>
`;
const parsedDoc = new DOMParser().parseFromString(html, "text/html");
const attributesToRemove = [
'ng-if',
'ng-model',
'ng-class',
];
attributesToRemove.forEach((attribName) => {
parsedDoc.querySelectorAll('[' + attribName + ']')
.forEach((elm) => elm.removeAttribute(attribName));
});
console.log(parsedDoc.body.innerHTML);

关于javascript - Javascript 的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50243838/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com