Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

javascript - 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.


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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...