JSONata:降低驼峰命名的单词

JSONata: words to lowerCamelCase

我有一个由单词和标点符号组成的字符串,例如“接受数据保护条款/条件(德语)”。我需要将其规范化为驼峰式,删除标点符号。

到目前为止,我最接近的尝试未能将单词驼峰式排列,我只能设法将它们变成烤肉串或 snake_case:

$normalizeId := function($str) <s:s> {
        $str.$lowercase()
            .$replace(/\s+/, '-')
            .$replace(/[^-a-zA-Z0-9]+/, '')
};

您应该定位前面有 space 的字母,并使用此正则表达式 /\s(.)/.

将它们大写

这是我的片段:(已编辑

(
    $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.

Link to playground

Anindya 的答案适用于您的示例输入,但如果 (German) 未大写,则会导致输出不正确:

"acceptDataProtectionTermsConditionsgerman"

Link to playground


此版本可以工作并防止该错误:

(
  $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