Would it be possible to change a string containing this line of HTML:
'<div _ngcontent-isd-c78="" pdroppable="formElements" ng-reflect-scope="formElements" id="divPanelId" style="color: red">DivContent</div>'
To this:
'<div id="divPanelId" style="color: red">DivContent</div>'
I want to remove _ngcontent-??
, pdroppable
, class
and ng-reflect-scope
.
Is it possible using JavaScript with Regex?
Note: _ngcontent-isd-c78
is changed randomly. For example, _ngcontent-sfw-c53
, _ngcontent-isw-c21
. So _ngcontent-????
where ????
is a random value
CodePudding user response:
If you have DOM access use it.
NOTE: If you mess with Angular attributes you can break things
const div = document.getElementById("divPanelId");
const keep = ["style","id"];
div.getAttributeNames().forEach(attr => {
if (keep.includes(attr)) return;
console.log("removing",attr)
div.removeAttribute(attr)
})
console.log(div.outerHTML)
<div _ngcontent-isd-c78="" pdroppable="formElements" ng-reflect-scope="formElements" id="divPanelId" style="color: red">DivContent</div>
CodePudding user response:
Here is a way to bring the html string into the DOM world, remove the unwanted attributes, and then convert it back to a string.
const inputDivStr = '<div _ngcontent-isd-c78="" pdroppable="formElements" ng-reflect-scope="formElements" id="divPanelId" style="color: red">DivContent</div>';
const parent = document.createElement('div');
parent.innerHTML = inputDivStr;
const divElem = parent.firstChild;
for (let attrName of divElem.getAttributeNames()) {
if (shouldRemoveAttr(attrName)) {
divElem.removeAttribute(attrName);
}
}
const outputDivStr = parent.innerHTML;
console.log(outputDivStr);
function shouldRemoveAttr(attrName) {
const regex = /_ngcontent-|pdroppable|class|ng-reflect-scope/;
return attrName.match(regex);
}
CodePudding user response:
you can use regex
var text = `<div _ngcontent-isd-c78="" pdroppable="formElements" ng-reflect-scope="formElements" id="divPanelId" style="color: red">DivContent</div>`;
const one = /_ngcontent-isd-c78="(.*?)"/;
const two = /pdroppable="(.*?)"/;
const three = //;
const four = /ng-reflect-scope="(.*?)"/;
text = text.replace(one, "").replace(two, "").replace(three, "").replace(four, "");
console.log(text)