如何在 Vue.js 中将驼峰式大小写转换为正确的大小写?
How to convert camel case to proper case in Vue.js?
我正在从 MongoDB collection 中检索数据并将数据填充到 ag-grid 中。我希望列 header 与 Spacing 大小写一致。最初,collection 有文本行 'businessAreaName',我希望它看起来像 'Business Area Name'。
我正在使用正则表达式的概念,但无法找出正确大小写的表达式。
headerName: x.replace(/_/g, ' ').replace(/\w\S*/g, function (txt)
{
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
})
上面的表达式给我输出 'Businessareaname'。任何类型的建议都将受到赞赏。
您真正需要做的就是
- 用 space 替换每个大写字符,然后是该字符
- 将第一个字符替换为大写
可以这样做:
const deCamelCase = str => str.replace(/[A-Z]/g, ' $&').replace(/^./, toUppercase);
const toUppercase = str => str.toUpperCase();
分解:
str => str.replace(/[A-Z]/g, ' $&')
这会匹配任何大写字符(仅限拉丁字母表!)并将其替换为包含 space 的字符串以及编码为 $&
的整个匹配字符串。请注意,我们需要使用 /g
标志来确保我们匹配每个实例。
str => str.replace(/^./, toUppercase)
这仅匹配字符串中的第一个字符,并使用 toUppercase
函数替换它,为了便于阅读,我将其定义在单独的一行中。
我正在从 MongoDB collection 中检索数据并将数据填充到 ag-grid 中。我希望列 header 与 Spacing 大小写一致。最初,collection 有文本行 'businessAreaName',我希望它看起来像 'Business Area Name'。
我正在使用正则表达式的概念,但无法找出正确大小写的表达式。
headerName: x.replace(/_/g, ' ').replace(/\w\S*/g, function (txt)
{
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
})
上面的表达式给我输出 'Businessareaname'。任何类型的建议都将受到赞赏。
您真正需要做的就是
- 用 space 替换每个大写字符,然后是该字符
- 将第一个字符替换为大写
可以这样做:
const deCamelCase = str => str.replace(/[A-Z]/g, ' $&').replace(/^./, toUppercase);
const toUppercase = str => str.toUpperCase();
分解:
str => str.replace(/[A-Z]/g, ' $&')
这会匹配任何大写字符(仅限拉丁字母表!)并将其替换为包含 space 的字符串以及编码为 $&
的整个匹配字符串。请注意,我们需要使用 /g
标志来确保我们匹配每个实例。
str => str.replace(/^./, toUppercase)
这仅匹配字符串中的第一个字符,并使用 toUppercase
函数替换它,为了便于阅读,我将其定义在单独的一行中。