我想将它们转换为以下:
1. Hello
2. Hello
3. HelloWorld
4. HelloWorld
5. HelloWorld
如果在字符串中没有空间,只有大写字母首先要小写。如果单词通过下划线或空间分开,则大写每个单词的第一字母,然后删除空间和下划线。我该如何在JavaScript中执行此操作。 thanks
这里是正则解决方案:第一个小写字符串:
str = str.toLowerCase();
将所有
str = str.replace(/(?:_| |\b)(\w)/g, function(str, p1) { return p1.toUpperCase()})
demo
update:少数步骤;)
解释:
/ // 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
可用,并且
您可以做这样的事情:
function toPascalCase(str) {
var arr = str.split(/\s|_/);
for(var i=0,l=arr.length; i<l; i++) {
arr[i] = arr[i].substr(0,1).toUpperCase() +
(arr[i].length > 1 ? arr[i].substr(1).toLowerCase() : "");
}
return arr.join("");
}
您可以在此处测试它,方法很简单,在找到空格或下划线时,将字符串变成数组。 然后循环穿过数组,上cas的第一个字母,降低其余的字母...然后将一系列标题单词添加到一个字符串中。
.split()
WorkingDemo:http://jsfiddle.net/ksje3/3/
Edit:代码的另一个版本 - 我用$ .map()替换Map():
WorkingDemo:http://jsfiddle.net/ksje3/4/ ANES6 /@nickcraver答案的功能更新。与 @Nickcraver的答案一样
function foo(str) {
return $(str.split(/\s|_/)).map(function() {
return this.charAt(0).toUpperCase() + this.slice(1).toLowerCase();
}).get().join("");
}
var city = city.replace(/\ s+/g,'')//将所有空间替换为Singele Speace city = city.replace(/\ w/g,city => city .touppercase())// speace letter convert copsitycapital
PUREJS(ES5)链接解决方案...没有以至于以下等级,没有jQuery,没有ES6
function foo(str) {
return $.map(str.split(/\s|_/), function(word) {
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
}).join("");
}