I am struggling on how to convert a string into camel case without apostrophe and white space. Here is my code so far:
function toCamelCase(input) {
return input
.toLowerCase()
.replace(/['W]+(.)?/g, (_, char) => (char ? char.toUpperCase() : ""))
.replace(/^./, (char) => char.toLowerCase());
}
const result2 = toCamelCase("HEy, world");
console.log(result2); // "heyWorld"
const result3 = toCamelCase("Yes, that's my student");
console.log(result3); // "yesThatsMyStudent"
""HEy, world"" works. The problem is that it is failing on "Yes, that’s my student". I got "yesThatSMyStudent" instead of "yesThatsMyStudent". I have no idea why the "s" in "that’s" is not lowercase. Can someone please explain why this is happening and point me in the right direction? Thank you.
Edit: Just for educational purpose, how would you handle a case if a word is quoted? For example, Yes, that's my 'student'
should be yesThatsMyStudent
.
2
Answers
You could assert not
'
before matching an optional char a-zOne could describe a pattern which looks for every word boundary followed by any sequence of non-letter but also non-single-quote characters which gets preceded by a single captured letter (
/b[^p{L}']+(p{L})/ug
). This matching pattern gets entirely replace by the uppercase variant of the captured letter. One then just needs to go after every remaining non-letter and non-number character (sequence) that each will be entirely removed/[^p{L}p{N}]/ug
…