Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all html style attributes with React compatible styles

I'm currently migrating my blog and want to replace all style attributes in my html with React compatible ones.

e.g.

<div style="display: flex; flex-direction: row; justify-content: flex-start">

needs to become.

<div style={{ display: "flex"; flexDirection: "row"; justifyContent: "flex-start" }}>

So - needs to be replaced with camelcasing in the keys. The values need to be wrapped with " and the " for the whole style attribute need to be replaced with {{ and }}.

So far I did following function.

function toReactStyle(str) {
  return str
    ?.toLowerCase()
    .replace(";", ",")
    .replace(/-(.)/g, function ($1) {
      return $1.toUpperCase();
    })
    .replace("-", "");
}


const $ = cheerio.load(node.value);
const div = $("div");
const style = div.attr("style");
div.attr("style", `{{${toReactStyle(style)}}}`);

However that doesn't cover the full desired result neither looks very efficient. No quotes arround values yet. Only first hyphen removed.

{{display: flex, justifyContent: flext-Start; align-Items: center;}}

I also tried finding some existing libraries that could do this operation for me, but couldn't find any so far. Is there anyone who knows of existing libraries that can do this or anyone with Rockstar Regex skills that can explain which Regex to use and how the Regex works?

The thing I struggle is to only wrap the values in quotes. and to only camelcase the keys and only remove the - from the keys.

like image 618
Marco Avatar asked Dec 02 '25 09:12

Marco


1 Answers

You can use

const $ = cheerio.load(node.value);
const div = $("div");
const style = div.attr("style");
const newstyle = "{{ " + s.replace( /([\w.-]+):\s*([^\s;]*)/g, (x,y,z) => `${y.replace(/-(.)/g, (m,n) => n.toUpperCase())}: "${z}"`) + "}}";
div.attr("style", newstyle);

The ([\w.-]+):\s*([^\s;]*) regex matches and captures the keys (into Group 1) and values (into Group 2), and then Group 1 value is converted to the required format and concatenated with the Group 2 value.

See the regex demo.

JavaScript demo:

const oldstyle = "display: flex; flex-direction: row; justify-content: flex-start";
console.log(
  "{{ " + oldstyle.replace( /([\w.-]+):\s*([^\s;]*)/g, (x,y,z) => `${y.replace(/-(.)/g, (m,n) => n.toUpperCase())}: "${z}"`) + "}}"
)
like image 159
Wiktor Stribiżew Avatar answered Dec 03 '25 21:12

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!