I have an array of strings with values in the Snake case.
I need them to map some inputs.
How can I convert
'some_string'
into 'Some String'
?
I have an array of strings with values in the Snake case.
I need them to map some inputs.
How can I convert
'some_string'
into 'Some String'
?
map()
over the input array
split('_')
: Convert string into an array on each _
map()
the array to make each first char uppercasejoin(' ')
: Convert the array back to a string, joined
on a space (
)const inputArray = [ 'some_string', 'foo_bar' ];
const outputArray = inputArray.map((input) => (
input.split('_').map(s => s.charAt(0).toUpperCase() + s.slice(1)).join(' ')
));
console.log(outputArray);
Input array:
[ 'some_string', 'foo_bar' ];
Will produce:
[
"Some String",
"Foo Bar"
]
You can Array.prototype.map() your array doing String.prototype.replace() with Regular expressions:
const arr = ['some_string', 'foo_bar']
const result = arr.map(
s => s
.replace(/_/g, ' ')
.replace(/^\w|\s\w/g, l => l.toUpperCase())
)
console.log(result)