10

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

2
  • @tvanfosson: You can edit if any thing is wrong. Thanks Commented Dec 18, 2010 at 13:38
  • done, and now I'll remove my comment since it doesn't make sense anymore. Commented Dec 18, 2010 at 13:41

6 Answers 6

14

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I have some good answers here. So +1 for all. But first answer is accepted. Thanks
The solution is the better of all, but I prefer to use //gi and remove the str = str.toLowerCase(); line.
12

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.

Comments

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

4 Comments

Why require jQuery for this? Also .map() is designed for jQuery objects, not regular arrays, use $.map() in that situation...though using jQuery at all here (unless already including it) isn't a good approach...and it's less efficient either way.
@Nick Yes, performance is lower. However, the code is smaller and more readable. If the OP uses jQuery on the page anyway, he should be fine with this solution.
I have some good answers here. So +1 for all. But first answer is accepted. Thanks
This will also remove any spaces or underscores on the string. aakil fernandes will become AakilFernandes
0

An ES6 / functional update of @NickCraver's answer. As with @NickCraver's answer this function will handle multiple spaces / underscores properly by filtering them out.

const pascalWord = x => x[0].toUpperCase() + x.slice(1).toLowerCase(); const toPascalCase2 = (str) => ( str.split(/\s|_/) .filter(x => x) .map(pascalWord) .join('') ); const tests = [ 'hello', 'HELLO', 'hello_world', 'HELLO_WORLD', 'Hello World', 'HELLO__WORLD__', 'Hello World_', ].map(toPascalCase2).join('<br>'); document.write(tests);

5 Comments

Why .filter(x => x)?
@MikeChamberlain It filters out blank strings ['Hello', '', 'World'].filter(x => x) = ['Hello', 'World']. There's probably a better way of doing it, but that's the most functional way I can think of.
And then in map you don't have to worry about empty strings
Ah, gotha. Yeah filter takes a predicate, so here coerces x to a boolean, which is false for blank strings. Perhaps !!x would be more idiomatic?
@MikeChamberlain Here's some novelty ways of doing the filter: stackoverflow.com/a/2843625/327074
0

var city = city.replace(/\s+/g,' ') //replace all spaceses to singele speace city = city.replace(/\b\w/g,city => city .toUpperCase()) //after speace letter convert capital

1 Comment

Welcome to SO! While this may answer the question, it could be more useful if you improved it a bit. Please take some time to check the formatting help and consider adding some info about what your code does
0

Pure JS (ES5) chaining solution... No regex, No jquery, No es6

function drop_n_cap(s) { function drop_em(v) { return v===' ' || v==='_' ? '' : v } function cap_em(v,i,a) { return ! a[i-1] ? v.toUpperCase() : v } return s.toLowerCase().split('').map(drop_em).map(cap_em).join('') } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.