Home > Net >  String in bracket all in caps
String in bracket all in caps

Time:07-10

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)

CodePudding user response:

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);

CodePudding user response:

You could use this answer to do something like:

_.startCase('Point of view (pov)').replace(/.*(\(.*\))/, function($0, $1) {return $0.replace($1, $1.toUpperCase());});

Or using an arrow function:

_.startCase('Point of view (pov)').replace(/.*(\(.*\))/, ($0, $1) => $0.replace($1, $1.toUpperCase()));

(I didn't see any need for the _.toLower().)

  • Related