我正在尝试创建一种方法,将带有小写字母和下划线的文本转换为没有下划线的文本,并且每个单词的首字母大写。
例如;
options_page = Options Page
在此页面:How to make first character uppercase of all words in JavaScript?
我找到了这个正则表达式:
key = key.replace(/(?:_| |\b)(\w)/g, function(key, p1) { return p1.toUpperCase()});
除了将下划线替换为空格之外,这会执行所有操作。我还没有真正尝试过任何东西,因为我对正则表达式不太熟悉。
我如何调整这个正则表达式,以便它用空格替换下划线?
最佳答案
这应该可以解决问题:
function humanize(str) {
var i, frags = str.split('_');
for (i=0; i<frags.length; i++) {
frags[i] = frags[i].charAt(0).toUpperCase() + frags[i].slice(1);
}
return frags.join(' ');
}
console.log(humanize('humpdey_dumpdey'));
// > Humpdey Dumpdey
回复
fiddle :
http://jsfiddle.net/marionebl/nf4NG/
jsPerf:
大部分测试数据:http://jsperf.com/string-transformations
所有版本加上 _.str:http://jsperf.com/string-transformations/3
关于javascript - 将下划线替换为空格并将单词大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21792367/