Skip to content

Instantly share code, notes, and snippets.

@sryze
Last active January 7, 2020 13:04
Show Gist options
  • Save sryze/f67687f045c4aa806cf9b59495aa57b6 to your computer and use it in GitHub Desktop.
Save sryze/f67687f045c4aa806cf9b59495aa57b6 to your computer and use it in GitHub Desktop.
Capitalize every word in a string
export function capitalizeWords(text) {
let result = '';
let wordCharIndex = 0;
for (let i = 0; i < text.length; i++) {
let c = text.charAt(i);
if (/\s/.test(c)) {
wordCharIndex = 0;
} else {
if (wordCharIndex == 0) {
c = c.toUpperCase();
} else {
c = c.toLowerCase();
}
wordCharIndex++;
}
result += c;
}
return result;
}
@Rajdeepc
Copy link

Rajdeepc commented Jan 7, 2020

This below line will throw error as it is a constant variable. Please change it to 'let'

Change from

const c = text.charAt(i);

Change To

let c = text.charAt(i);

@sryze
Copy link
Author

sryze commented Jan 7, 2020

I updated the code, thanks @Rajdeepc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment