简体   繁体   English

如何在Vue.js中将驼峰大小写转换为适当的大小写?

[英]How to convert camel case to proper case in Vue.js?

I am retrieving data from MongoDB collection & filling the data in ag-grid. 我正在从MongoDB集合中检索数据,并将数据填充到ag-grid中。 I want the column header to be in proper case with Spacing. 我希望列标题在适当情况下使用Spacing。 Initially, the collection has text line 'businessAreaName' and I want it to look like 'Business Area Name'. 最初,该集合具有文本行“ businessAreaName”,我希望它看起来像“ Business Area Name”。

I am using the concept of regular expression but not able to figure out expression for proper case. 我正在使用正则表达式的概念,但无法找出适当情况下的表达式。

headerName: x.replace(/_/g, ' ').replace(/\w\S*/g, function (txt) 
  { 
    return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); 
  })

The expression above is giving me output as 'Businessareaname'. 上面的表达式使我输出为“ Businessareaname”。 Any kind of suggestion is appreciated. 任何形式的建议,我们将不胜感激。

All you really need to do is 您真正需要做的就是

  1. replace every uppercase character with a space, followed by that character 用空格替换每个大写字符,然后跟该字符
  2. replace the first character with uppercase 用大写字母替换第一个字符

This can be done like so: 可以这样完成:

const deCamelCase = str => str.replace(/[A-Z]/g, ' $&').replace(/^./, toUppercase);
const toUppercase = str => str.toUpperCase();

Breaking this down: 分解如下:

str => str.replace(/[A-Z]/g, ' $&')

This matches any uppercase character (latin alphabet only!) and replaces it with a string consisting of a space, plus the whole matched string, coded as $& . 这将匹配任何大写字符(仅拉丁字母!),并将其替换为包含空格的字符串以及整个匹配的字符串,编码为$& Note that we need to use the /g flag to make sure we match every instance. 请注意,我们需要使用/g标志来确保我们匹配每个实例。

str => str.replace(/^./, toUppercase)

This matches the first character in the string only, and replaces it using the toUppercase function, which I define on a separate line for readability. 这仅匹配字符串中的第一个字符,并使用toUppercase函数替换该toUppercase ,为了便于阅读,我在一行中定义了toUppercase函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM