javascript - 将所有 html 样式属性替换为 React 兼容样式
问题描述
我目前正在迁移我的博客,并希望将我的 html 中的所有样式属性替换为与 React 兼容的属性。
例如
<div style="display: flex; flex-direction: row; justify-content: flex-start">
需要成为。
<div style={{ display: "flex"; flexDirection: "row"; justifyContent: "flex-start" }}>
因此-
需要在键中替换为驼峰式。这些值需要被包裹起来,"
并且"
整个样式属性的 需要被替换为{{
and }}
。
到目前为止,我做了以下功能。
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 如何工作?
我挣扎的事情是只用引号将值括起来。并且只将钥匙放在驼峰上,并且只-
从钥匙中取出。
解决方案
您可以使用
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 组值连接。
请参阅正则表达式演示。
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}"`) + "}}"
)
推荐阅读
- visual-studio - 使用 Qemu 在 Ubuntu 上的 Visual Studio Professional 远程调试 Arm64 程序
- sql - SQL Server 透视所有表列
- html - Flex div 没有占据其父级的全高
- apache - .htaccess Vanity/Nice URLs 导致 404 错误成为主页
- javascript - 如何通过仅在用户滚动到特定部分时调用它来减少谷歌地图 API 命中数
- excel - 如果工作表中的一个单元格不等于0,我该如何做减法
- laravel - 不能一下子在 laravel 宅基地上流浪
- javascript - 在 bit.dev 上安装一个导出的组件时未定义 React
- javascript - 如何在对数图表类型中禁用科学记数法
- jquery - 更新输入和窗口加载时在多个位置更新文本