Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
113
rated 0 times [  116] [ 3]  / answers: 1 / hits: 18256  / 14 Years ago, sat, december 18, 2010, 12:00:00

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


More From » string

 Answers
6

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.


[#94556] Thursday, December 16, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
timothyc

Total Points: 233
Total Questions: 103
Total Answers: 103

Location: Jordan
Member since Thu, Aug 5, 2021
3 Years ago
;