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
The toUpperCase() method converts a string to uppercase letters. The toUpperCase() method does not change the original string.
Use the INITCAP() function to convert a string to a new string that capitalizes the first letter of every word. All other letters will be lowercase. This function takes one parameter as a string and changes the capitalization for each word as described.
To capitalize the first letter of each word in an array:Use the map() method to iterate over the array. On each iteration, use the toUpperCase() method on the first character of the word and concatenate the rest. The map method will return a new array with all words capitalized.
CamelCase Words are written without spaces, and the first letter of each word is capitalized. Also called Upper Camel Case or Pascal Casing. lowerCamelCase A variation of Camel Case in which the fist letter of the word is lowercase, e.g. iPhone, iPad, etc.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With