Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 577
Smokey Dawson Avatar asked Feb 10 '26 08:02

Smokey Dawson


2 Answers

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);
like image 95
Ahmet Can Güven Avatar answered Feb 12 '26 22:02

Ahmet Can Güven


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);
like image 25
CertainPerformance Avatar answered Feb 12 '26 21:02

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!