Reputation: 3142
I have a string consisting of words and punctuation, such as "Accept data protection terms / conditions (German)". I need to normalize that to camelcase, removing punctuation.
My closest attempt so far fails to camelcase the words, I only manage to make them into kebab-case or snake_case:
$normalizeId := function($str) <s:s> {
$str.$lowercase()
.$replace(/\s+/, '-')
.$replace(/[^-a-zA-Z0-9]+/, '')
};
Upvotes: 1
Views: 519
Reputation: 1101
You should target the letters which has a space in front, and capitalize them by using this regex /\s(.)/
.
Here is my snippet: (Edited
(
$upper := function($a) {
$a.groups[0].$uppercase()
};
$normalizeId := function($str) <s:s> {
$str.$lowercase()
.$replace(/[^-a-zA-Z0-9]+/, '-')
.$replace(/-(.)/, $upper)
.$replace(/-/, '')
};
$normalizeId("Accept data protection terms / conditions (German)");
)
/* OUTPUT: "acceptDataProtectionTermsConditionsGerman" */
Edit: Thanks @vitorbal. The "$lower" function on regex replacement earlier was not necessary, and did not handle the scenario you mentioned. Thanks for pointing that out. I have updated my snippet as well as added a link to the playground below.
Upvotes: 1
Reputation: 3031
Anindya's answer works for your example input, but if (German)
was not capitalized, it would result in the incorrect output:
"acceptDataProtectionTermsConditionsgerman"
This version would work and prevent that bug:
(
$normalizeId := function($str) <s:s> {
$str
/* normalize everything to lowercase */
.$lowercase()
/* replace any "punctuations" with a - */
.$replace(/[^-a-zA-Z0-9]+/, '-')
/* Find all letters with a dash in front,
strip the dash and uppercase the letter */
.$replace(/-(.)/, function($m) { $m.groups[0].$uppercase() })
/* Clean up any leftover dashes */
.$replace("-", '')
};
$normalizeId($$)
/* OUTPUT: "acceptDataProtectionTermsConditionsGerman" */
)
Upvotes: 2