Reputation: 353
I am trying to clean up angular code to send it later to jsPDF. jsPDF usually fails when not recognize HTML code is found, so I am trying to get rid of it.
So far the expression would it be something like
'<code>'.replace(/ng-\w+="(\w|\d\s)+"/,'')
This is useful for simple things but I need a more elaborated expressions and I haven't been able to come across it.
ng-\w+="
#Finds expressions like ng-if, ng-model, ng-class, etc
(\w|\d\s)+
#This expressions only accepts spaces, numbers and digits
What I really need is to get all the content in between the double quotes
Upvotes: 2
Views: 123
Reputation: 64657
Expanding on the other answer...
You could use a DOMParser
, then use a treeWalker
to iterate through all of the nodes and remove any attribute that starts with ng-
:
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 el = new DOMParser().parseFromString(html, "text/html");
var treeWalker = document.createTreeWalker(
el,
NodeFilter.SHOW_ELEMENT,
{ acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } },
false
);
var nodeList = [];
while(treeWalker.nextNode()) {
Array.apply(null, treeWalker.currentNode.attributes).
filter(a => a.name.startsWith('ng-')).
forEach((attr, index) => {
treeWalker.currentNode.removeAttribute(attr.name);
});
}
console.log(el.documentElement.querySelector('body').innerHTML);
Upvotes: 1
Reputation: 370639
Why not use DOMParser instead, like this? Better not to try to parse HTML with regex
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);
Upvotes: 1