Javascript method for changing snake_case to PascalCase

后端 未结 5 1419
遥遥无期
遥遥无期 2021-01-18 22:33

I\'m looking for a JS method that will turn snake_case into PascalCase while keeping slashes intact.

// examples:
post -> Post
a         


        
5条回答
  •  广开言路
    2021-01-18 22:55

    Here's a solution that preserves slashes and converts snake_case to PascalCase like you want.

    const snakeToPascal = (string) => {
      return string.split("/")
        .map(snake => snake.split("_")
          .map(substr => substr.charAt(0)
            .toUpperCase() +
            substr.slice(1))
          .join(""))
        .join("/");
    };
    

    It first splits the input at the '/' characters to make an array of snake_case strings that need to be transformed. It then splits those strings at the '_' characters to make an array of substrings. Each substring in this array is then capitalized, and then rejoined into a single PascalCase string. The PascalCase strings are then rejoined by the '/' characters that separated them.

提交回复
热议问题