在 Javascript 中将字符串转换为帕斯卡大小写(又名 UpperCamelCase)
我想知道如何将字符串转换为 javascript 中的帕斯卡大小写字符串(最有可能是正则表达式)。
转换示例:
- double-barrel = 双筒
- DOUBLE-BARREL = 双筒
- DoUbLE-BaRRel = 双筒 双筒
- = 双筒
检查 此链接了解有关 Pascal Case 的更多信息
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
正则表达式查找单词(此处使用
\w
定义 - 字母数字和下划线),并将它们分为两组 - 第一个字母和单词的其余部分。然后它使用一个函数作为回调来设置正确的情况。示例: http://jsbin.com/uvase
或者,这也可以工作 - 少一点正则表达式,多一点字符串操作:
我应该补充一点,这根本不是帕斯卡大小写,因为你有单词障碍(
helloworld
vshello-world
)。没有它们,即使有字典,这个问题也几乎无法解决。尽管它不处理“FBI”、“the”或“McDonalds”等单词,但更常称为“标题首字母大写”。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:
I should add this isn't pascal case at all, since you have word barriers (
helloworld
vshello-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".这是我的建议:
或
测试用例:
Here's my suggestion:
or
Test cases:
如果破折号、空格等是字符串分隔符,可以使用 lodash。
例如
In case dash, space and other are string separators one may use lodash.
e.g.
我从 Kobi 的回答开始,并使用了kalicki2k的答案 踢轮胎。
可以通过将
az
更改为\p{L}
,并添加u
标志:仅通过启用 unicode 的版本才能通过的两个附加测试:
顺便说一句,非 unicode 版本大约是两倍与 unicode 版本一样快kalicki2k 的版本。这并不重要,它们都足够快。
如果您需要缓存:
缓存加多语言:
这些版本在基准测试中似乎要快得多(8 倍),但这当然不能很好地代表实际使用情况。
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 theu
flag:Two additional tests that only pass with the unicode-enabled version:
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:
Caching plus multilingual:
These versions appear to be much faster (8x) in a benchmark, but of course that's not a good representation of real-world use.
由于不同语言的字符不同,您可能会在其他答案的解决方案中遇到困难。您可以使用此方法来解决这些麻烦。
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.
此答案的单行 Typescript 版本,它还处理空/未定义的字符串:
A one-line Typescript version of this answer, which also handles the string being null/undefined:
带有修剪空间选项的简单版本:
测试:
Simpler version with trim space option:
Tests: