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
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:
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