在 Javascript 中将字符串转换为帕斯卡大小写(又名 UpperCamelCase)

发布于 2024-09-29 17:07:32 字数 286 浏览 1 评论 0 原文

我想知道如何将字符串转换为 javascript 中的帕斯卡大小写字符串(最有可能是正则表达式)。

转换示例:

  • double-barrel = 双筒
  • DOUBLE-BARREL = 双筒
  • DoUbLE-BaRRel = 双筒 双筒
  • = 双筒

检查 此链接了解有关 Pascal Case 的更多信息

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

Conversion Examples:

  • double-barrel = Double-Barrel
  • DOUBLE-BARREL = Double-Barrel
  • DoUbLE-BaRRel = Double-Barrel
  • double barrel = Double Barrel

Check this link for further info on Pascal Case

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

嗼ふ静 2024-10-06 17:07:32
s = s.replace(/(\w)(\w*)/g,
        function(g0,g1,g2){return g1.toUpperCase() + g2.toLowerCase();});

正则表达式查找单词(此处使用 \w 定义 - 字母数字和下划线),并将它们分为两组 - 第一个字母和单词的其余部分。然后它使用一个函数作为回调来设置正确的情况。

示例: http://jsbin.com/uvase

或者,这也可以工作 - 少一点正则表达式,多一点字符串操作:

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

我应该补充一点,这根本不是帕斯卡大小写,因为你有单词障碍(helloworld vs hello-world)。没有它们,即使有字典,这个问题也几乎无法解决。尽管它不处理“FBI”、“the”或“McDonalds”等单词,但更常称为“标题首字母大写”。

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".

迷爱 2024-10-06 17:07:32

这是我的建议:

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

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

测试用例:

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');
    chai.assert.equal(toPascalCase('Here i am'), 'HereIAm');
    chai.assert.equal(toPascalCase('FOO BAR'), 'FooBar');
  });
});

Here's my suggestion:

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

or

String.prototype.toPascalCase = function() {
  return this
    .toLowerCase()
    .replace(new RegExp(/[-_]+/, 'g'), ' ')
    .replace(new RegExp(/[^\w\s]/, 'g'), '')
    .replace(
      new RegExp(/\s+(.)(\w*)/, 'g'),
      ($1, $2, $3) => `${$2.toUpperCase() + $3}`
    )
    .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');
    chai.assert.equal(toPascalCase('Here i am'), 'HereIAm');
    chai.assert.equal(toPascalCase('FOO BAR'), 'FooBar');
  });
});
烟─花易冷 2024-10-06 17:07:32

如果破折号、空格等是字符串分隔符,可以使用 lodash

例如

_.upperFirst(_.camelCase('double-barrel')); // => DoubleBarrel

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

e.g.

_.upperFirst(_.camelCase('double-barrel')); // => DoubleBarrel
物价感观 2024-10-06 17:07:32
function toPascalCase (str) {
  if (/^[a-z\d]+$/i.test(str)) {
    return str.charAt(0).toUpperCase() + str.slice(1);
  }
  return str.replace(
    /([a-z\d])([a-z\d]*)/gi,
    (g0, g1, g2) => g1.toUpperCase() + g2.toLowerCase()
  ).replace(/[^a-z\d]/gi, '');
}

我从 Kobi 的回答开始,并使用了kalicki2k的答案 踢轮胎。

可以通过将 az 更改为 \p{L},并添加 u 标志

function toPascalCase (str) {
  if (/^[\p{L}\d]+$/iu.test(str)) {
    return str.charAt(0).toUpperCase() + str.slice(1);
  }
  return str.replace(
    /([\p{L}\d])([\p{L}\d]*)/giu,
    (g0, g1, g2) => g1.toUpperCase() + g2.toLowerCase()
  ).replace(/[^\p{L}\d]/giu, '');
}

仅通过启用 unicode 的版本才能通过的两个附加测试:

chai.assert.equal(toPascalCase('ça.roule'), 'ÇaRoule');
chai.assert.equal(toPascalCase('добрий-день'), 'ДобрийДень');

顺便说一句,非 unicode 版本大约是两倍与 unicode 版本一样快kalicki2k 的版本。这并不重要,它们都足够快。

如果您需要缓存:

const pascalCache = {};
function toPascalCase (str) {
    pascalCache[str] =
        pascalCache[str] ||
        (
            /^[a-z\d]+$/i.test(str) &&
            str.charAt(0).toUpperCase() + str.slice(1)
        ) ||
        str.replace(
            /([a-z\d])([a-z\d]*)/gi,
            (g0, g1, g2) => g1.toUpperCase() + g2.toLowerCase()
        ).replace(/[^a-z\d]/gi, '');

    return pascalCache[str];
}

缓存加多语言:

const pascalCache = {};
function toPascalCase (str) {
    pascalCache[str] =
        pascalCache[str] ||
        (
            /^[\p{L}\d]+$/iu.test(str) &&
            str.charAt(0).toUpperCase() + str.slice(1)
        ) ||
        str.replace(
            /([\p{L}\d])([\p{L}\d]*)/giu,
            (g0, g1, g2) => g1.toUpperCase() + g2.toLowerCase()
        ).replace(/[^\p{L}\d]/giu, '');

    return pascalCache[str];
}

这些版本在基准测试中似乎要快得多(8 倍),但这当然不能很好地代表实际使用情况。

function toPascalCase (str) {
  if (/^[a-z\d]+$/i.test(str)) {
    return str.charAt(0).toUpperCase() + str.slice(1);
  }
  return str.replace(
    /([a-z\d])([a-z\d]*)/gi,
    (g0, g1, g2) => g1.toUpperCase() + g2.toLowerCase()
  ).replace(/[^a-z\d]/gi, '');
}

I started with Kobi's answer, and used the Chai tests from kalicki2k's answer to kick the tires.

Crude multilingual support can be added by changing a-z to \p{L}, and adding the u flag:

function toPascalCase (str) {
  if (/^[\p{L}\d]+$/iu.test(str)) {
    return str.charAt(0).toUpperCase() + str.slice(1);
  }
  return str.replace(
    /([\p{L}\d])([\p{L}\d]*)/giu,
    (g0, g1, g2) => g1.toUpperCase() + g2.toLowerCase()
  ).replace(/[^\p{L}\d]/giu, '');
}

Two additional tests that only pass with the unicode-enabled version:

chai.assert.equal(toPascalCase('ça.roule'), 'ÇaRoule');
chai.assert.equal(toPascalCase('добрий-день'), 'ДобрийДень');

Incidentally, the non-unicode version is roughly twice as fast as the unicode-version & kalicki2k's version. Which doesn't really matter, they are all plenty fast.

If you need caching:

const pascalCache = {};
function toPascalCase (str) {
    pascalCache[str] =
        pascalCache[str] ||
        (
            /^[a-z\d]+$/i.test(str) &&
            str.charAt(0).toUpperCase() + str.slice(1)
        ) ||
        str.replace(
            /([a-z\d])([a-z\d]*)/gi,
            (g0, g1, g2) => g1.toUpperCase() + g2.toLowerCase()
        ).replace(/[^a-z\d]/gi, '');

    return pascalCache[str];
}

Caching plus multilingual:

const pascalCache = {};
function toPascalCase (str) {
    pascalCache[str] =
        pascalCache[str] ||
        (
            /^[\p{L}\d]+$/iu.test(str) &&
            str.charAt(0).toUpperCase() + str.slice(1)
        ) ||
        str.replace(
            /([\p{L}\d])([\p{L}\d]*)/giu,
            (g0, g1, g2) => g1.toUpperCase() + g2.toLowerCase()
        ).replace(/[^\p{L}\d]/giu, '');

    return pascalCache[str];
}

These versions appear to be much faster (8x) in a benchmark, but of course that's not a good representation of real-world use.

要走干脆点 2024-10-06 17:07:32

由于不同语言的字符不同,您可能会在其他答案的解决方案中遇到困难。您可以使用此方法来解决这些麻烦。

const toPascalCase = (str) => {
  let tempArray = str.split(" ");
  tempArray = tempArray.map(
    (value) => value.charAt(0).toUpperCase() + value.slice(1, value.length)
  );
  return tempArray.join("");
};

You may experience difficulties in the solutions in other answers due to different characters in different languages. You can use this method to solve these troubles.

const toPascalCase = (str) => {
  let tempArray = str.split(" ");
  tempArray = tempArray.map(
    (value) => value.charAt(0).toUpperCase() + value.slice(1, value.length)
  );
  return tempArray.join("");
};
单调的奢华 2024-10-06 17:07:32

此答案的单行 Typescript 版本,它还处理空/未定义的字符串:

const toPascalCase = (s: string | null | undefined) =>
  s ? s.replace(/(\w)(\w*)/g, (_, p, q) => p.toUpperCase() + q.toLowerCase()) : s;

A one-line Typescript version of this answer, which also handles the string being null/undefined:

const toPascalCase = (s: string | null | undefined) =>
  s ? s.replace(/(\w)(\w*)/g, (_, p, q) => p.toUpperCase() + q.toLowerCase()) : s;
哆啦不做梦 2024-10-06 17:07:32

带有修剪空间选项的简单版本:

const toPascalCase = (text, trimSpace=false) => text.split(' ').map((t) => t[0].toUpperCase() + t.slice(1).toLowerCase()).join(trimSpace?'':' ')

测试:

const toPascalCase = (text, trimSpace=false) => text.split(' ').map((t) => t[0].toUpperCase() + t.slice(1).toLowerCase()).join(trimSpace?'':' ')

console.log(toPascalCase('hello world')); // Output: "Hello World"
console.log(toPascalCase('foo bar baz')); // Output: "Foo Bar Baz"
console.log(toPascalCase('this is a sample text')); // Output: "This Is A Sample Text"

Simpler version with trim space option:

const toPascalCase = (text, trimSpace=false) => text.split(' ').map((t) => t[0].toUpperCase() + t.slice(1).toLowerCase()).join(trimSpace?'':' ')

Tests:

const toPascalCase = (text, trimSpace=false) => text.split(' ').map((t) => t[0].toUpperCase() + t.slice(1).toLowerCase()).join(trimSpace?'':' ')

console.log(toPascalCase('hello world')); // Output: "Hello World"
console.log(toPascalCase('foo bar baz')); // Output: "Foo Bar Baz"
console.log(toPascalCase('this is a sample text')); // Output: "This Is A Sample Text"

蓝色星空 2024-10-06 17:07:32
const toPascalCase = (sentence) => sentence
   .toLowerCase()
   .replace(new RegExp(/[-_]+/, 'g'), ' ')
   .replace(new RegExp(/[^\w\s]/, 'g'), '')
   .trim()
   .split(' ')
   .map(word => word[0]
   .toUpperCase()
   .concat(word.slice(1)))
   .join('');

toPascalCase(words);
const toPascalCase = (sentence) => sentence
   .toLowerCase()
   .replace(new RegExp(/[-_]+/, 'g'), ' ')
   .replace(new RegExp(/[^\w\s]/, 'g'), '')
   .trim()
   .split(' ')
   .map(word => word[0]
   .toUpperCase()
   .concat(word.slice(1)))
   .join('');

toPascalCase(words);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文