我已经搜索了解决方案,但还没有找到。
我有以下字符串。
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()})
更新:步骤更少;)
解释:
/ // 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/