Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
430 views
Welcome To Ask or Share your Answers For Others

1 Answer

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}"`) + "}}"
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...