Convert string to Pascal Case (aka UpperCamelCase) in Javascript

I like to know how I can hide the line in the case pascal line in javascript (& most probally regex).

Conversion Examples:

  • double barrel = double barrel
  • DOUBLE-BARrel = Double-Barrel
  • DoUbLE-BaRrel = Double-Barrel
  • double barrel = double barrel

Check out this link for more information on Case Pascal.

+5
source share
2 answers
s = s.replace(/(\w)(\w*)/g,
        function(g0,g1,g2){return g1.toUpperCase() + g2.toLowerCase();});

( \w - alphanumerics ) - . .

: http://jsbin.com/uvase

- :

s = s.replace(/\w+/g,
        function(w){return w[0].toUpperCase() + w.slice(1).toLowerCase();});

, , (helloworld vs hello-world). . Title Case, , "FBI", "the" "McDonalds".

+15

, :

function pascal (str, match) {
return str.split(' ').map(function(word){
    let i = word.search(match);
    return word.charAt(0).toUpperCase() + word.slice(1, i - 1) + word.charAt(i).toUpperCase() + word.slice(i + 1);
  }).join('');

}

:

pascal('someservice', 'service') // 'SomeService'
0

All Articles