在Javascript中将字符串转换为Pascal Case(又名UpperCamelCase) [英] Convert string to Pascal Case (aka UpperCamelCase) in Javascript

查看:633
本文介绍了在Javascript中将字符串转换为Pascal Case(又名UpperCamelCase)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在javascript(&最常见的正则表达式)中将字符串转换为pascal case字符串。

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

转换示例:


  • double-barrel = Double-Barrel

  • DOUBLE-BARREL = Double-Barrel

  • DoUbLE-BaRRel = Double-Barrel

  • double barrel = Double Barrel

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

查看此链接以获取有关Pascal案例的更多信息

Check this link for further info on Pascal Case

推荐答案

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

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

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.

示例: 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();});

我应该添加这不是pascal的情况,因为你有字障碍( helloworld vs hello-world )。没有它们,即使使用字典,问题也几乎无法解决。这通常被称为标题案例,虽然它不处理像FBI,the或McDonalds这样的词。

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

这篇关于在Javascript中将字符串转换为Pascal Case(又名UpperCamelCase)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆