【问题标题】:Replace all html style attributes with React compatible styles将所有 html 样式属性替换为 React 兼容样式
【发布时间】:2021-04-07 16:44:54
【问题描述】:

我目前正在迁移我的博客,并希望将我的 html 中的所有样式属性替换为与 React 兼容的属性。

例如

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

需要成为。

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

所以- 需要替换为键中的驼峰式。值需要用" 包裹,整个样式属性的" 需要用{{}} 替换。

到目前为止,我做了以下功能。

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)}}}`);

但是,这并没有涵盖完整的预期结果,看起来也不是很有效。还没有围绕值的引号。仅删除了第一个连字符。

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

我还尝试找到一些可以为我执行此操作的现有库,但到目前为止找不到。有没有人知道现有的库可以做到这一点,或者有 Rockstar Regex 技能的人可以解释使用哪个 Regex 以及 Regex 如何工作?

我挣扎的事情是只将值括在引号中。并且只对键进行驼峰式处理,并且只从键中删除 -

【问题讨论】:

标签: javascript html css reactjs regex


【解决方案1】:

你可以使用

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

([\w.-]+):\s*([^\s;]*) 正则表达式匹配并捕获键(进入第 1 组)和值(进入第 2 组),然后将第 1 组值转换为所需格式并与第 2 组值连接。

请参阅regex demo

JavaScript 演示:

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

【讨论】:

  • 谢谢,成功了,所以 () 之间的所有都是捕获组。 x 是完整捕获,y,z 是捕获组。
猜你喜欢
  • 2017-08-30
  • 2019-08-13
  • 1970-01-01
  • 1970-01-01
  • 2011-07-27
  • 2015-10-25
  • 1970-01-01
  • 1970-01-01
  • 2016-09-01
相关资源
最近更新 更多