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
.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){
return string.replaceAll('_', ' ').replaceAll(/(^\w|\s\w)/g, firstCharOfWord => firstCharOfWord.toUpperCase());
}
let formattedString = formatString('sample_orders')
console.log(formattedString) //Sample Orders
Caveat: You might encounter an error saying .replaceAll is not a function if you are running on an older browser or runtime environment.
The .replaceAll method was added in ES2021/ES12. The best workaround to run such functionalities on older versions of JS is to provide native support to older versions that do not support newly added methods or features ( .replaceAll) in this case.
function formatString(string){
return string.replace(/_/g, ' ').replace(/(^\w|\s\w)/g, firstCharOfWord => firstCharOfWord.toUpperCase());
}
let formattedString = formatString('sample_orders')
console.log(formattedString) //Sample Orders
Note that we're using the replace method with regular expressions on a global scope. This could also be used at instances where the strings might not contain underscores.