admin管理员组文章数量:1398206
I want to write a function which can change any type of string case i.e lower case, UPPER CASE, camelCase, snake_case, lisp-case into Title Case
I am not looking for something bvery plicated, just a simple one or two liner.
I tried using soem regexp such as this
function(input) {
return input.replace(/([^\W_]+[^\s_]*) */g, function(txt){
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
};
It works for some cases but does not work in all cases
I want to write a function which can change any type of string case i.e lower case, UPPER CASE, camelCase, snake_case, lisp-case into Title Case
I am not looking for something bvery plicated, just a simple one or two liner.
I tried using soem regexp such as this
function(input) {
return input.replace(/([^\W_]+[^\s_]*) */g, function(txt){
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
};
It works for some cases but does not work in all cases
Share Improve this question edited Dec 12, 2014 at 10:05 Mohan asked Dec 12, 2014 at 9:50 MohanMohan 4,8297 gold badges46 silver badges70 bronze badges 02 Answers
Reset to default 6function titleCase(s) {
return s
.replace(/([^A-Z])([A-Z])/g, '$1 $2') // split cameCase
.replace(/[_\-]+/g, ' ') // split snake_case and lisp-case
.toLowerCase()
.replace(/(^\w|\b\w)/g, function(m) { return m.toUpperCase(); }) // title case words
.replace(/\s+/g, ' ') // collapse repeated whitespace
.replace(/^\s+|\s+$/, ''); // remove leading/trailing whitespace
}
Example:
['UPPER CASE', 'camelCase', 'snake_case', 'lisp-case'].map(titleCase)
// result: ["Upper Case", "Camel Case", "Snake Case", "Lisp Case"]
Try this:
var titleCase = oldString
.replace(/([a-z])([A-Z])/g, function (allMatches, firstMatch, secondMatch) {
return firstMatch + " " + secondMatch;
})
.toLowerCase()
.replace(/([ -_]|^)(.)/g, function (allMatches, firstMatch, secondMatch) {
return (firstMatch ? " " : "") + secondMatch.toUpperCase();
}
);
Working Fiddle
Working Fiddle2
本文标签: Change any type of string to Title Case in JavascriptStack Overflow
版权声明:本文标题:Change any type of string to Title Case in Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744174120a2593918.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论