0

I have a string Hello <span style="color: rgb(241, 18, 45); background-color: rgb(173, 250, 9);">Reac<span style="font-weight: bold;">t</span></span> I want to remove the color property and its value leaving all the other styles as it is when i pass color. (from all the span)

If I pass font-weight it must remove all the font-weight and its value.

For example: Lets say when I pass "color", output of the above string must be:

Hello <span style="background-color: rgb(173, 250, 9);">Reac<span style="font-weight: bold;">t</span></span>

I tried using :

html = myString.replace(new RegExp(`\\s*${props}\\s*:[^;]*[;"]`, "ig"), "");

where, props is style property i want to remove. Example "color"

Problem in the above code is it remove the color from the background-color as well.

prabhu
  • 878
  • 9
  • 17
shiva shukla
  • 119
  • 2
  • 11

2 Answers2

3

Although you could get a long way with regular expressions, it is better practice to rely on a proven HTML parser. And the Web API has one: DOMParser:

function removeCSS(s, cssProp) {
    let doc = new DOMParser().parseFromString(s, "text/html");
    for (let elem of doc.querySelectorAll("*")) elem.style.removeProperty(cssProp);
    return doc.body.innerHTML;
}

let s = `Hello <span style="color: rgb(241, 18, 45); background-color: rgb(173, 250, 9);">Reac<span style="font-weight: bold;">t</span></span>`;
let result = removeCSS(s, "color");
console.log(result);
trincot
  • 317,000
  • 35
  • 244
  • 286
0

I think you may use html = myString.replace(/(?<=\"|;|\s){props}\:[^;]*;/, "");

(?<=\"|;|\s){props} is a Lookbehind assertion, which will match if props is after " ; or a space. In this way, background-color won't be included in the matches.

Alan
  • 121
  • 2
  • I would not confirm the use of regular expression. Imagine how it can miss valid CSS, just because there is a space following the property, or the attribute was enclosed in single quotes instead of double quotes, or for some reason HTML entities were used instead of plain characters. Imagine the false positives when exactly this text appears as ... text in text nodes, not in attributes, or in HTML comments, or in script tags, or... etc, ...etc. It is very hard, if not, impossible, to write a bullet proof regular expression for this. [see this](https://stackoverflow.com/a/1732454/5459839) – trincot Jul 18 '20 at 14:59