How to make first character uppercase of all words in JavaScript?

I have searched for solution but did not find yet.

I have the following string.

1. hello
2. HELLO
3. hello_world
4. HELLO_WORLD
5. Hello World

I want to convert them to following:

1. Hello
2. Hello
3. HelloWorld
4. HelloWorld
5. HelloWorld

If there is No space and underscore in string just uppercase first and all others to lowercase. If words are separated by underscore or space then Uppercase first letter of each word and remove space and underscore. How can I do this in JavaScript.

Thanks


You could do something like this:

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("");
}

You can test it out here, the approach is pretty simple, .split() the string into an array when finding either whitespace or an underscore. Then loop through the array, upper-casing the first letter, lower-casing the rest...then take that array of title-case words and .join() it together into one string again.


Here is a regex solution:

First lowercase the string:

 str = str.toLowerCase();

Replace all _ and spaces and first characters in a word with upper case character:

 str = str.replace(/(?:_| |b)(w)/g, function(str, p1) { return p1.toUpperCase()})

DEMO

Update: Less steps ;)

Explanation:

/            // 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

The value of the capturing group is available as p1 in the function, and the whole expression is replaced by the return value of the function.


function foo(str) {
    return $(str.split(/s|_/)).map(function() {
        return this.charAt(0).toUpperCase() + this.slice(1).toLowerCase();
    }).get().join("");
}

Working demo: http://jsfiddle.net/KSJe3/3/ (I used Nicks regular expression in the demo)


Edit: Another version of the code - I replaced map() with $.map():

function foo(str) {
    return $.map(str.split(/s|_/), function(word) {
        return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
    }).join("");
}

Working demo: http://jsfiddle.net/KSJe3/4/

链接地址: http://www.djcxy.com/p/37758.html

上一篇: 如何在使用Jquery的最后一个正斜杠之前获取值

下一篇: 如何使JavaScript中的所有单词的第一个字符大写?