Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JSONata: words to lowerCamelCase

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]+/, '')
};

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Anindya’s answer works for your example input, but if (German) was not capitalized, it would result in the incorrect output:

"acceptDataProtectionTermsConditionsgerman"

Link to playground


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" */
)

Link to playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading