Home > Software design >  How do I convert lowercase and underscores to proper case and spaces in ES6/React
How do I convert lowercase and underscores to proper case and spaces in ES6/React

Time:10-16

How do I convert strings with underscores into spaces and converting it to proper case?

CODE

 const string = sample_orders

 console.log(string.replace(/_/g, ' '))

Expected Output

Sample Orders

CodePudding user response:

This function should do the job :

function humanize(str) {
  var i, frags = str.split('_');
  for (i=0; i<frags.length; i  ) {
    frags[i] = frags[i].charAt(0).toUpperCase()   frags[i].slice(1);
  }
  return frags.join(' ');
}


humanize('sample_orders');
// > Sample Orders

JSFiddle

CodePudding user response:

.replace replace only the first occurrence of the target input. In order to replace all the occurrences, use .replaceAll.

 var string = 'sample_orders'

 string = string.replaceAll('_', ' ')

Further converting it to the proper case could be accomplished through regEx

string = string.replace(/(^\w|\s\w)/g, firstCharOfWord => firstCharOfWord.toUpperCase());

Where:

  • ^\w : First char of the string
  • | : or
  • \s\w : First char after whitespace
  • g : global scope(Match all occurrences)
  • The second argument is a function that accepts the first character of each word computed using the regular expression and converts it to an upper case. Binding the above logic into a function:
    function formatString(string){
     
     string = string.replaceAll('_', ' ') //sample orders
     string = string.replace(/(^\w|\s\w)/g, firstCharOfWord => firstCharOfWord.toUpperCase());
     
     return string
    }
    
    let formattedString = formatString('sample_orders')
    console.log(formattedString) //Sample Orders
    
    • Related