Search code examples
camelcasingjsonata

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

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