Smokey Dawson
Smokey Dawson

Reputation: 9240

convert string with spaces into string with no spaces and camelCase javascript

Is there a way I can turn this string

let string = 'I have some spaces in it'; 

into

string = 'iHaveSomeSpacesInIt';

I know I can use

string.split(' ').join('');

to take all the spaces out of the string but how can I transform the first uppercase letter to lowercase and then camelCase at all the spaces that have been removed??

Any help would be appreciated!

Thanks

Upvotes: 3

Views: 3267

Answers (3)

Ahmet Can Güven
Ahmet Can Güven

Reputation: 5462

Maybe regex can help you lot more faster and produce a more clear code.

var regex = /\s+(\w)?/gi;
var input = 'I have some spaces in it';

var output = input.toLowerCase().replace(regex, function(match, letter) {
    return letter.toUpperCase();
});

console.log(output);

Upvotes: 7

Kunal Mukherjee
Kunal Mukherjee

Reputation: 5853

Use a specialized library like Lodash for this type of requirement instead of writing a custom logic:

let string = 'I have some spaces in it';
let finalString = _.camelCase(string);

console.log(finalString);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 371138

Sure, just map each word (except the first) and capitalize the first letter:

const input = 'I have some spaces in it'; 
const output = input
  .split(' ')
  .map((word, i) => {
    if (i === 0) return word.toLowerCase();
    return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
  })
  .join('');
console.log(output);

Upvotes: 2

Related Questions