javascript - 如何使JavaScript中所有单词的第一个字符大写?

标签 javascript string

我已经搜索了解决方案,但还没有找到。

我有以下字符串。

1. hello
2. HELLO
3. hello_world
4. HELLO_WORLD
5. Hello World

我想将它们转换为以下内容:

1. Hello
2. Hello
3. HelloWorld
4. HelloWorld
5. HelloWorld

如果字符串中没有空格和下划线,则大写优先,其他全部小写。如果单词由下划线或空格分隔,则每个单词的首字母大写并删除空格和下划线。我如何在 JavaScript 中执行此操作。

谢谢

最佳答案

这是一个正则表达式解决方案:

首先将字符串小写:

 str = str.toLowerCase();

用大写字符替换单词中的所有 _ 和空格和第一个字符:

 str = str.replace(/(?:_| |\b)(\w)/g, function(str, p1) { return p1.toUpperCase()})

DEMO

更新:步骤更少;)

解释:

/            // start of regex
 (?:         // starts a non capturing group
   _| |\b    // match underscore, space, or any other word boundary character 
             // (which in the end is only the beginning of the string ^)
  )          // end of group
 (           // start capturing group
  \w         // match word character
 )           // end of group
/g           // and of regex and search the whole string

捕获组的值在函数中作为p1可用,整个表达式被函数的返回值替换。

关于javascript - 如何使JavaScript中所有单词的第一个字符大写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4478227/

相关文章:

PHP 多字节 str_replace?

c - 如何统计字符串中该序列出现的次数?

python - 用星号替换字符串中的所有字符

javascript - $location.path 重定向到错误的位置

javascript - Vue.js "track-by $index",如何单独渲染列表项

javascript - 为什么需要变量名 "$scope"?

java - 如何获取字符串的第一个字符

javascript - 是否有任何关于让 HTML5 Canvas 在 IE9 中工作的提示?

javascript - 在渲染器中加载组合框字段的存储时出现问题

c++ - 从 std::string 中删除所有 xml 标签