Convert string to Pascal Case (aka UpperCamelCase) in Javascript

前端 未结 3 1171
清歌不尽
清歌不尽 2020-12-10 01:13

Id like to know how I can covert a string into a pascal case string in javascript (& most probally regex).

Conversion Examples:

  • double-barrel = Dou
相关标签:
3条回答
  • 2020-12-10 01:24

    In case dash, space and other are string separators one may use lodash.

    e.g.

    _.upperFirst(_.camelCase('double-barrel')); // => DoubleBarrel
    
    0 讨论(0)
  • 2020-12-10 01:26

    Here's my suggestion:

    function toPascalCase(string) {
      return `${string}`
        .replace(new RegExp(/[-_]+/, 'g'), ' ')
        .replace(new RegExp(/[^\w\s]/, 'g'), '')
        .replace(
          new RegExp(/\s+(.)(\w+)/, 'g'),
          ($1, $2, $3) => `${$2.toUpperCase() + $3.toLowerCase()}`
        )
        .replace(new RegExp(/\s/, 'g'), '')
        .replace(new RegExp(/\w/), s => s.toUpperCase());
    }
    

    or

    String.prototype.toPascalCase = function() {
      return this
        .replace(new RegExp(/[-_]+/, 'g'), ' ')
        .replace(new RegExp(/[^\w\s]/, 'g'), '')
        .replace(
          new RegExp(/\s+(.)(\w+)/, 'g'),
          ($1, $2, $3) => `${$2.toUpperCase() + $3.toLowerCase()}`
        )
        .replace(new RegExp(/\s/, 'g'), '')
        .replace(new RegExp(/\w/), s => s.toUpperCase());
    };
    

    Test cases:

    describe('String to pascal case', function() {
      it('should return a pascal cased string', function() {
        chai.assert.equal(toPascalCase('foo bar'), 'FooBar');
        chai.assert.equal(toPascalCase('Foo Bar'), 'FooBar');
        chai.assert.equal(toPascalCase('fooBar'), 'FooBar');
        chai.assert.equal(toPascalCase('FooBar'), 'FooBar');
        chai.assert.equal(toPascalCase('--foo-bar--'), 'FooBar');
        chai.assert.equal(toPascalCase('__FOO_BAR__'), 'FooBar');
        chai.assert.equal(toPascalCase('!--foo-¿?-bar--121-**%'), 'FooBar121');
      });
    });
    
    0 讨论(0)
  • 2020-12-10 01:41
    s = s.replace(/(\w)(\w*)/g,
            function(g0,g1,g2){return g1.toUpperCase() + g2.toLowerCase();});
    

    The regex finds words (here defined using \w - alphanumerics and underscores), and separates them to two groups - first letter and rest of the word. It then uses a function as a callback to set the proper case.

    Example: http://jsbin.com/uvase

    Alternately, this will also work - a little less regex and more string manipulation:

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

    I should add this isn't pascal case at all, since you have word barriers (helloworld vs hello-world). Without them, the problem is almost unsolvable, even with a dictionary. This is more commonly called Title Case, though it doesn't handle words like "FBI", "the" or "McDonalds".

    0 讨论(0)
提交回复
热议问题