2

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'?

Alex
  • 455
  • 1
  • 5
  • 14

2 Answers2

3
  1. map() over the input array

    1. split('_'): Convert string into an array on each _
    2. map() the array to make each first char uppercase
    3. join(' '): 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"
]
0stone0
  • 34,288
  • 4
  • 39
  • 64
  • 1
    Not the downvoter, but a comment since I happened to be looking at code that did the exact same thing in another answer on SO where the performance was tested, apparently it's faster to do `s[0]` than `charAt(0)`. (Now that I've looked at the stats again, it's barely worth mentioning, difference is negligible.) – 404 Sep 23 '21 at 15:36
1

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)
3limin4t0r
  • 19,353
  • 2
  • 31
  • 52
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
  • 1
    I've removed the trailing `]` so it won't produce an error. But OP want each word to start with an uppercase, in your answer only the first one is capitalised. – 0stone0 Sep 23 '21 at 15:32
  • 1
    @0stone0 thank you.. I have fixed – Yosvel Quintero Sep 23 '21 at 15:49
  • 2
    Note that this answer only works for base ASCII characters. `\w` only matches `[a-zA-Z0-9_]`, meaning that `"nightwish_élan"` would be converted to `"Nightwish élan"`. This might or might not be an issue depending on your scenario. – 3limin4t0r Sep 23 '21 at 16:11