Search code examples
javascriptnode.jsreactjslodash

String in bracket all in caps


I have a use case where I want to control all the char in the bracket to uppercase.

For example, if there's a string Laugh out Loud (lol) I want to convert it to Laugh Out Loud (LOL)

something like this, Where applying in a string first letter to be cap and if bracket then it should all convert into all caps.

Few examples: Point of view (pov) to Point Of View (POV)

What the hell to What The Hell

it should also work if only string without brackets.

how can I achieve this in JS?

I am able to achieve it to put all the letter caps _.startCase(_.toLower('Point of view (pov)'))

The result is Point Of View (pov)


Solution

  • You can achieve this if you first split ths string with empty string and then if it starts with ('(') and ends with (')') then you uppercase whole string else upper case only first character

    const str = 'Laugh out Loud (lol)';
    const result = str
        .split(' ')
        .map((s) =>
            s.startsWith('(') && s.endsWith(')')
                ? s.toUpperCase()
                : s.slice(0, 1).toUpperCase() + s.slice(1),
        )
        .join(' ');
    console.log(result);