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 0
Add a ment  | 

2 Answers 2

Reset to default 6
function 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