代码之家  ›  专栏  ›  技术社区  ›  dragi

在Javascript中将不同的字符串转换为大小写

  •  -1
  • dragi  · 技术社区  · 8 年前

    我知道我们有一个类似的问题,但不完全相同。 我试图使我的函数工作,它接受一个字符串作为参数,并将其转换为大小写。它在大多数情况下都很管用 !?<>=

    当我传递像 snakeCase . 它回来了 snakecase 而不是 snake_case

    我试着去实现它,但结果却把它搞砸了。。

    我能帮忙吗?

    我的代码:

    const snakeCase = string => {
        string = string.replace(/\W+/g, " ").toLowerCase().split(' ').join('_');
    
        if (string.charAt(string.length - 1) === '_') {
            return string.substring(0, string.length - 1);
        }
    
        return string;
    }
    
    1 回复  |  直到 8 年前
        1
  •  10
  •   CertainPerformance    8 年前

    您需要能够检测大写字母在另一个字母后面的字符串中的位置(即,不在空格后面)。你可以用正则表达式来实现, 你打电话来 toLowerCase 在输入字符串上:

    \B(?=[A-Z])
    

    换句话说,一个非单词边界,后跟一个大写字符。在上面或文本空间上拆分, 然后 .map

    const snakeCase = string => {
        return string.replace(/\W+/g, " ")
          .split(/ |\B(?=[A-Z])/)
          .map(word => word.toLowerCase())
          .join('_');
    };
    
    console.log(snakeCase('snakeCase'));
        2
  •  3
  •   Subhojit Mondal    6 年前

    Hello World? 您希望返回值为 hello_world?

    const snakeCase = (string) => {
      return string.replace(/\d+/g, ' ')
        .split(/ |\B(?=[A-Z])/)
        .map((word) => word.toLowerCase())
        .join('_');
    };
    

    snakeCase('Hello World?')
    // "hello_world?"
    
    snakeCase('Hello & World')
    // "hello_&_world"
    
        3
  •  0
  •   Stan Smulders    5 年前

    我认为这个应该包括所有的基地

    它的灵感来自@h0r53对公认答案的回答。然而,它演变成一个更完整的功能,因为它将转换 任何 camelCase kebab-case snake_case 就像你所期望的那样,只包含 a-z 和 0-9 字符,可用于函数名和变量名:

    convert_to_snake_case(string) {
        return string.charAt(0).toLowerCase() + string.slice(1) // lowercase the first character
          .replace(/\W+/g, " ") // Remove all excess white space and replace & , . etc.
          .replace(/([a-z])([A-Z])([a-z])/g, "$1 $2$3") // Put a space at the position of a camelCase -> camel Case
          .split(/\B(?=[A-Z]{2,})/) // Now split the multi-uppercases customerID -> customer,ID
          .join(' ') // And join back with spaces.
          .split(' ') // Split all the spaces again, this time we're fully converted
          .join('_') // And finally snake_case things up
          .toLowerCase() // With a nice lower case
      }
    

    转换示例:

    'snakeCase'                  => 'snake_case'
    'CustomerID'                 => 'customer_id'
    'GPS'                        => 'gps'
    'IP-address'                 => 'ip_address'
    'Another & Another, one too' => 'another_another_one_too'
    'random ----- Thing123'      => 'random_thing123'
    'kebab-case-example'         => 'kebab_case_example'