驼峰式字符串转换为普通字符串

时间:2019-06-18 09:22:25

标签: javascript node.js ecmascript-6

如何更改NoOfSAP => No of SAP?我已经尝试过replace方法,但是它说的是undefined。

function unCamlelCase(result) {
  return result.key.replace(/([^A-Z]*)([A-Z]*)([A-Z])([^A-Z]*)/g, '$1 $2 $3$4')
    .replace(/ +/g, ' ');
};

如何将结果键值的驼峰式大小写更改为普通字符串?

if (exactMatch) {
  const { ...response } = json[0];
  const result = Object.keys(response).reduce((acc, key) => {let newKey = key.charAt(0).toUpperCase() + key.slice(1);
  return acc;
}, {});

2 个答案:

答案 0 :(得分:2)

您可以将以下表达式与一些辅助方法一起使用以清理输出:

"NoOfSAP".split(/([A-Z][a-z]+)/).filter(Boolean).join(' ');

这将匹配所有大写字母,然后是一个或多个小写字母,并将每个块分成一个数组。然后,.filter(Boolean)用于删除数组中的任何空字符串,然后.join用于在数组中的字符串之间添加空格。

请参见下面的示例:

const getWords = wrd =>
  wrd.split(/([A-Z][a-z]+)/).filter(Boolean).join(' ');
  
console.log(getWords("NoOfSAP")); // No Of SAP
console.log(getWords("ThisIsAWord")); // This Is A Word (notice how it will split individual letters such as A)
console.log(getWords("IAmAHuman")); // I Am A Human
console.log(getWords("JSIsGreat")); // JS Is Great (notice how it understands JS and Is are two seperate words and doesn't give JSI s Great)

根据您有关将对象中的键更改为“不带大小写”键的问题,可以将.mapObject.keys结合使用来生成结果:

const getWords = wrd =>
  wrd.split(/([A-Z][a-z]+)/).filter(Boolean).join(' ');
  
const obj = {
  "NoOfSAP": 1,
  "NoOfBUN": 2,
  "NoOfBRE": 3,
  "NoOfPEA": 4
}

const result = Object.keys(obj).map(getWords);
console.log(result);

答案 1 :(得分:1)

您可以这样做:

const camelToWords = (camelCaseWord) => camelCaseWord
  .replace(/([A-Z]+)/g, " $1")
  .replace(/([A-Z][a-z])/g, "$1");

还可以使用lodash之类的现有库:

const _ = require('lodash');
console.log(_.startCase('abcDef'));
// result: Abc Def