js 驼峰与下划线互转

/**
     * 驼峰转下划线
     */
    function replaceUppercaseWithUnderscoresAndLowercase (str) {
      return str.replace(/[A-Z]/g, (match) => `_${match.toLowerCase()}`)
    }

    const originalStr = "helloWorld";
    const replacedStr = replaceUppercaseWithUnderscoresAndLowercase(originalStr);
    console.log(replacedStr); // 输出: "hello_world"
    /**
     * 下划线转驼峰
     */
    function replaceUnderscoresAndLowercaseWithUppercase(str) {
      return str.replace(/_[a-z]/g, match => match.toUpperCase()).replace("_","");
    }
    
    const originalStr = "hello_world";
    const replacedStr = replaceUnderscoresAndLowercaseWithUppercase(originalStr);
    console.log(replacedStr); // 输出: "helloWorld"

 

posted @ 2024-11-27 10:17  岁月记忆  阅读(14)  评论(0编辑  收藏  举报