1

Would it be possible to change a string containing this line of HTML:

'<div _ngcontent-isd-c78="" pdroppable="formElements" class="panel" 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

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Hasan Kaan TURAN
  • 391
  • 2
  • 13

3 Answers3

3

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" class="panel" ng-reflect-scope="formElements" id="divPanelId" style="color: red">DivContent</div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
2

you can use regex

var text = `<div _ngcontent-isd-c78="" _ngcontent-isd-c80=""  _ngcontent-whd-c50="asdad" pdroppable="formElements" class="panel" ng-reflect-scope="formElements" id="divPanelId" style="color: red">DivContent</div>`;
        
            const one = /(.?)ngcontent(.*?)="(.*?)"/g;
            const two = /pdroppable(.*?)="(.*?)"/g;
            const three = /class="(.*?)"/g;
            const four = /ng-reflect-scope(.*?)="(.*?)"/g;
            text = text.replace(one, "").replace(two, "").replace(three, "").replace(four, "");
            console.log(text)
Salim Baskoy
  • 591
  • 5
  • 11
1

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" class="panel" 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);
}
Rocky Sims
  • 3,523
  • 1
  • 14
  • 19