Reputation: 11
Is it possible to run a callback function with specific start and stop indexes? I am practicing my JS and am writing a function to convert strings to camel case (from being '-' or '_' seperated) without altering the capitalization of the first word in the string. Basically, after I split the string into an array of words, I want to call .map() and start my callback on the second word in the array. currently I have:
function toCamelCase(str){
return str.split(/\-|_/).map(word => word.charAt(0).toUpperCase() + word.slice(1)).join('');
}
How can I get .map()
to begin at str.split(/\-|_/)[1]
?
Upvotes: 0
Views: 209
Reputation: 7100
In simple words, you can't. .map
will iterate over an entire array.
You can chain .map
to .slice
though
function toCamelCase(str, start, stop){
return str.split(/\-|_/).slice(start, stop).map(word => word.charAt(0).toUpperCase() + word.slice(1)).join('');
}
Upvotes: 2
Reputation: 192467
Array.map()
always iterates the entire array. You can use the index (2nd param in callback) to return the word without changes if the index is 0:
function toCamelCase(str){
return str.split(/\-|_/).map((word, i) => i ? word.charAt(0).toUpperCase() + word.slice(1) : word).join('');
}
console.log(toCamelCase('the_camels_toes'));
BTW - you can use a regular expression with String.replace()
to to create the camel case:
function toCamelCase(str){
return str.replace(/_(\w)/g, (_, c) => c.toUpperCase());
}
console.log(toCamelCase('the_camels_toes'));
Upvotes: 0