最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

convert string with spaces into string with no spaces and camelCase javascript - Stack Overflow

programmeradmin1浏览0评论

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

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

Share Improve this question asked May 4, 2018 at 6:31 Smokey DawsonSmokey Dawson 9,24022 gold badges85 silver badges162 bronze badges 1
  • 1 split the string-make it as an array-capitalise first character of each array's value-join together to make a camel context string. – Krishna Prashatt Commented May 4, 2018 at 6:34
Add a ment  | 

3 Answers 3

Reset to default 7

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);

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);

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./ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

发布评论

评论列表(0)

  1. 暂无评论