Camelcase string to normal string

Viewed 276

How to change NoOfSAP => No Of SAP? I have trying the replace method but it says undefined.

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

How can I change the result key values camel case to normal string?

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 Answers

You could use the following expression with a few helper methods to clean up the output:

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

This will match all upper case letters followed by one or more lower-case letters and split each chunk into an array. .filter(Boolean) is then used to remove any empty strings in the array and .join is then used to add spaces between the strings in the array.

See example below:

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)

As per your question about changing the keys in your object to the "uncamelcased" keys you can use .map with Object.keys to generate your result:

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

You can go that way:

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

There is also possibility to use existing libraries like lodash:

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