9

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

tvanfosson
  • 524,688
  • 99
  • 697
  • 795
Awan
  • 18,096
  • 36
  • 89
  • 131

5 Answers5

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.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • I have some good answers here. So +1 for all. But first answer is accepted. Thanks – Awan Dec 18 '10 at 14:05
  • The solution is the better of all, but I prefer to use `//gi` and remove the `str = str.toLowerCase();` line. – Diosney Jul 30 '13 at 17:27
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.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
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/

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
  • 1
    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 Craver Dec 18 '10 at 13:55
  • @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. – Šime Vidas Dec 18 '10 at 14:04
  • I have some good answers here. So +1 for all. But first answer is accepted. Thanks – Awan Dec 18 '10 at 14:05
  • This will also remove any spaces or underscores on the string. `aakil fernandes` will become `AakilFernandes` – A F Oct 30 '14 at 15:37
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);
Community
  • 1
  • 1
icc97
  • 11,395
  • 8
  • 76
  • 90
  • Why `.filter(x => x)`? – Mike Chamberlain Mar 13 '17 at 09:25
  • @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. – icc97 Mar 13 '17 at 09:27
  • And then in `map` you don't have to worry about empty strings – icc97 Mar 13 '17 at 09:29
  • 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? – Mike Chamberlain Mar 13 '17 at 12:20
  • @MikeChamberlain Here's some novelty ways of doing the `filter`: http://stackoverflow.com/a/2843625/327074 – icc97 Mar 14 '17 at 23:18
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
    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](https://stackoverflow.com/editing-help) and consider adding some info about what your code does – Mario Trucco Aug 22 '17 at 12:53