Search code examples
javascriptregexcontenteditable

How can i manipulate the string in javaScript?


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.


Solution

  • 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);