[英]Replace underscores with spaces and capitalize words
我正在尝试创建一种方法将带有小写字母和下划线的文本转换为没有下划线的文本,并且每个单词的第一个字母都大写。
前任;
options_page = Options Page
在此页面: 如何使 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(' ');
}
humanize('humpdey_dumpdey');
// > Humpdey Dumpdey
复制
小提琴:
http://jsfiddle.net/marionebl/nf4NG/
jsPerf :
大多数测试数据: http : //jsperf.com/string-transformations
所有版本加上 _.str : http : //jsperf.com/string-transformations/3
从 Lodash 3.1.0 开始,有一个_.startCase([string=''])
方法可以将任何大小写转换为大写单词(起始大小写):
_.startCase('hello_world'); // returns 'Hello World'
_.startCase('hello-world'); // returns 'Hello World'
_.startCase('hello world'); // returns 'Hello World'
Lodash 的 String 部分还有其他有用的方法。 阅读此处的文档。
这是两个不同的任务,所以两个不同的正则表达式是最好的解决方案:
key = key.replace(/_/g, ' ').replace(/(?: |\b)(\w)/g, function(key) { return key.toUpperCase()});
以确保处理所有大写单词。 您可以在第一个.replace
之前添加.toLowerCase()
:
console.log('TESTING_WORD'.toLowerCase().replace(/_/g, ' ') .replace(/(?: |\\b)(\\w)/g, function(key, p1) { return key.toUpperCase(); }));
另一种选择:
camel = "options_page".replace(/(^|_)(\\w)/g, function ($0, $1, $2) { return ($1 && ' ') + $2.toUpperCase(); }); console.log(camel);
正则表达式:
(^|_) beginning of the input OR "_" ($1)
(\w) a word character (short for [a-zA-Z0-9_]) ($2)
g all occurrences (global)
有关正则表达式的更多信息: http : //www.javascriptkit.com/javatutors/redev.shtml 。
这里:
var str = 'Lorem_ipsum_dolor_sit_amet,_consectetur____adipiscing_elit.'
str = str.replace(/_{1,}/g,' ').replace(/(\s{1,}|\b)(\w)/g, function(m, space, letter)
{
return space + letter.toUpperCase();
})
console.log(str);
只需添加 . replace('_',' ')
像这样
function toCamel(string){
return string.replace(/(?:_| |\b)(\w)/g, function($1){return $1.toUpperCase().replace('_',' ');});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.