如何在JavasScript中将字符串转换为脊柱案例?

时间:2016-04-16 00:02:25

标签: javascript regex str-replace

我遇到了来自freeCodeCamp的编码挑战Spinal Tap Case。基本上我不知道如何执行最后一次检查。

这是最后一次检查: localStorage

这是我的代码:

spinalCase("AllThe-small Things") should return "all-the-small-things"

我确实认识到最后function spinalCase(str) { var outputString, newstr, pattern1 = new RegExp(/[_\s]/, 'g'), pattern2 = new RegExp(/(?=[A-Z])/, 'g'), stringTest1 = pattern1.test(str), stringTest2 = pattern2.test(str); if(stringTest1) { outputString = str.replace(pattern1, '-'); newstr = outputString.toLowerCase(); } else if(stringTest2) { str.split(/(?=[A-Z])/).join(' '); outputString = str.replace(pattern2, '-'); newstr = outputString.toLowerCase(); } else if (stringTest1 && stringTest2){ outputString = str.replace(pattern1, '-'); outputString = str.replace(pattern2, '-'); newstr = outputString.toLowerCase(); } return newstr; } 条件应该先行,但我没有正确的语法。

提前致谢!

10 个答案:

答案 0 :(得分:4)

这是我的解决方案,简单使用正则表达式,适用于所有情况

function spinalCase(str) {
  return str.replace(/([A-Z])/g,' $1') /*Find all cap and add space at the start*/
        .replace(/[^A-Za-z0-9]/g,' ') /*Find all non alpha numeric and replace it with space*/
        .replace(/\s{1,}/g,"-") /*Convert all spaces to -*/
        .replace(/^\-|[\-]$/g,'') /*Slice - at the start and end*/
        .toLowerCase(); /*LowerCase it*/
}

答案 1 :(得分:3)

以下是我推荐的方法:

function sp(str) {
  var spinal = str.replace(/(?!^)([A-Z])/g, ' $1')
                .replace(/[_\s]+(?=[a-zA-Z])/g, '-').toLowerCase();
  return spinal 
}

JsBin Example

就您的代码而言,请检查:

如果test1 else if test2,则else if test1 and test2,逻辑不正确:

您可以尝试向第一个添加!test2!test1,如果检查可以使其正常工作:

if (stringTest1 && !stringTest2)...

编辑:

以下是如何让你的代码在最后的代码中触发,如果我在那里放一个console.log来向你展示:

JSBin Example

function spinalCase(str) {
    var outputString, 
              newstr,
              pattern1 = new RegExp(/[_\s]/, 'g'),
              pattern2 = new RegExp(/(?=[A-Z])/, 'g'),
              stringTest1 = pattern1.test(str),
              stringTest2 = pattern2.test(str);

         if(stringTest1 && !stringTest2)  {
                outputString = str.replace(pattern1, '-');
                newstr = outputString.toLowerCase();
          } else if(!stringTest1 && stringTest1) {
               str.split(/(?=[A-Z])/).join(' ');
                outputString = str.replace(pattern2, '-');
                newstr = outputString.toLowerCase();
          } else if (stringTest1 && stringTest2){
                console.log('were in the last else!!!');
                outputString = str.replace(pattern1, '-');
                outputString = str.replace(pattern2, '-');
                newstr = outputString.toLowerCase();
          }

  return newstr;

}

答案 2 :(得分:1)

这是我的解决方案,对正则表达式的重视程度稍低:

function spinalCase(str) {
  var newStr = str[0];

  for (var j = 1; j < str.length; j++) {
    // if not a letter make a dash
    if (str[j].search(/\W/) !== -1 || str[j] === "_") {
      newStr += "-";
    }
    // if a Capital letter is found 
    else if (str[j] === str[j].toUpperCase()) {
      // and preceded by a letter or '_'
      if (str[j-1].search(/\w/) !== -1 && str[j-1] !== "_") {
        // insert '-' and carry on
        newStr += "-";
        newStr += str[j];
      }
      else {
        newStr += str[j];
      }
    }
    else {
        newStr += str[j];
    }
  }

  newStr = newStr.toLowerCase();
  return newStr;
}

答案 3 :(得分:1)

function spinalCase(str) {

  // any string followed by upperCase letter
  var  re = /(?=[A-Z])/g;  

  // any string followed by space and upperCase/lowerCase letter 
  var  re2=/(?=\s[A-Z]|\s[a-z])/g;

  // any string of 2 or more '-'
  var re3 = new RegExp("-{2,}", "g");

  var space = new RegExp(" ","g");
  var hyphen = new RegExp("_","g");

  str = str.replace(hyphen,"-");
  str = str.replace(re, '-');   
  str = str.replace(re2,"-");
  str = str.replace(re3,"-"); 
  str = str.replace(space,"");
  str = str.toLowerCase();
  if(str.slice(0,1)== '-'){
    str = str.replace("-","");  
  }     
  return str;
}

spinalCase('This Is Spinal Tap');

答案 4 :(得分:1)

function spinalCase(str) {
  var newStr = '';
  var arr = str.split('');
  for (var i = 0; i < arr.length; i += 1) {
    if (i > 0) {
      if (arr[i] >= 'A' && arr[i] <= 'Z') {
        if (arr[i - 1] >= 'a' && arr[i - 1] <= 'z') {
          newStr += '-';
          newStr += arr[i].toLowerCase();
          continue;
        }
      }
      else if (arr[i] === ' ' || arr[i] === '_') {
        newStr += '-';
        continue;
      }
    }
    newStr += arr[i].toLowerCase();
  }
  return newStr;
}

spinalCase("AllThe-small Things");

答案 5 :(得分:1)

function spinalCase(str) {
//Split the string at one of the following conditions 
        //a whitespace character [\s] is encountered
        //underscore character [_] is encountered
        //or by an uppercase letter [(?=[A-Z])]
//Join the array using a hyphen (-)
//Lowercase the whole resulting string 

   return str.split(/\s|_|(?=[A-Z])/).join('-').toLowerCase(); 

}

答案 6 :(得分:1)

我也坚持这样做,但是找到了一个更简单的解决方案:

import numpy as np
from numba import njit, prange

dtype_complex = np.complex64

@njit
def _perm(matrix):
    n = matrix.shape[0]
    d = np.ones(n, dtype=dtype_complex)
    j =  0
    s = 1
    f = np.arange(n)
    v = matrix.sum(axis=0)
    p = np.prod(v)
    while (j < n - 1):
        v -= 2 * d[j]*matrix[j]
        d[j] = -d[j]
        s = -s
        prod = np.prod(v)
        p += s * prod
        f[0] = 0
        f[j] = f[j+1]
        f[j+1] = j + 1
        j = f[0]
    return p / 2 ** (n - 1)

@njit
def _get_elements(one_over_det, matrix, lefts, rights):
    length = len(lefts)
    to_perm = np.zeros((length, length), dtype=dtype_complex)

    for idx1, lbit_idx1 in enumerate(lefts):
        for idx2, lbit_idx2 in enumerate(rights):
            to_perm[idx1, idx2] = one_over_det * matrix[lbit_idx2, lbit_idx1]
    return _perm(to_perm)

@njit
def _get_result(t, L, B, ener, evec, f_mat, I, site1, site2):

    result = 0.0 + 0.0j
    for a in np.arange(L):
        for b in np.arange(L):
            for e in np.arange(L):
                for f in np.arange(L):
                    H_abef = 2 * (B[:,a] - B[:,b] + B[:,e] - B[:,f])

                    f_exp_H_abef_t = f_mat @ (np.diag(np.exp(1j * H_abef * t)).astype(dtype_complex))

                    to_inv = I + f_mat - f_exp_H_abef_t
                    inv = np.linalg.inv(to_inv)

                    one_over_det = 1.0 / np.linalg.det(to_inv)
                    matrix = f_exp_H_abef_t @ inv

                    phase1 = np.exp(1j * (
                        ener[a] - ener[b] + ener[e] - ener[f]
                        - B[a, a] - B[b, b] - B[e, e] - B[f, f]
                        + 2 * (
                            + B[a, b] + B[e, f]
                            + B[f, a] + B[f, b]
                            - B[e, a] - B[e, b]
                        )
                    ) * t)

                    for c in np.arange(L):
                        for d in np.arange(L):

                            phase2 = np.exp(2j * (
                                B[f, c] + B[f, d] - B[e, c] - B[e, d]
                            ) * t)

                            for g in np.arange(L):
                                for h in np.arange(L):

                                    # 8th order term
                                    elements = _get_elements(one_over_det, matrix, [a, c, e, g], [b, d, f, h])

                                    # 6th order terms
                                    if b == c: elements += _get_elements(one_over_det, matrix, [a, e, g], [d, f, h])

                                    if d == e: elements += _get_elements(one_over_det, matrix, [a, c, g], [b, f, h])

                                    if b == e: elements += _get_elements(one_over_det, matrix, [a, c, g], [d, f, h])

                                    if f == g: elements += _get_elements(one_over_det, matrix, [a, c, e], [b, d, h])

                                    if d == g: elements += _get_elements(one_over_det, matrix, [a, c, e], [b, f, h])

                                    if b == g: elements += _get_elements(one_over_det, matrix, [a, c, e], [d, f, h])

                                    # quartic terms
                                    if b == e and f == g: elements += _get_elements(one_over_det, matrix, [a, c], [d, h])

                                    if b == e and d == g: elements += _get_elements(one_over_det, matrix, [a, c], [f, h])

                                    if b == c and f == g: elements += _get_elements(one_over_det, matrix, [a, e], [d, h])

                                    if b == c and d == g: elements += _get_elements(one_over_det, matrix, [a, c], [f, h])

                                    if d == e and f == g: elements += _get_elements(one_over_det, matrix, [a, c], [b, h])

                                    if b == c and d == e: elements += _get_elements(one_over_det, matrix, [a, g], [f, h])

                                    if d == e and b == g: elements += _get_elements(one_over_det, matrix, [a, c], [f, h])

                                    # quadratic term
                                    if b == c and d == e and f == g: elements += one_over_det * matrix[h, a]

                                    unitary = evec[site2, a] * evec[site2, b] \
                                            * evec[site1, c] * evec[site1, d] \
                                            * evec[site2, e] * evec[site2, f] \
                                            * evec[site1, g] * evec[site1, h]
                                    
                                    result += unitary * phase1 * phase2 * elements
    
    return result

答案 7 :(得分:1)

初学者友好的解决方案:

function spinalCase(str) {
//change camelCase to title case(i.e. change 'markIsHere' to 'Mark Is Here') 
    let newStr = str.replace(/([a-z])([A-Z])/g, ('$1 $2'));
//replace space with '-'
    newStr = newStr.replace(/ /g, '-');
//replace underscores with '-'
    newStr = newStr.replace(/_/g,'-');
//change the result to lowercase
    return newStr.toLowerCase()
}

答案 8 :(得分:0)

function spinalCase(str) {

  // Create a variable for the white space and underscores
  var regex = /\s+|_+/g;

  // Replace low-upper case to low-space-uppercase
  str = str.replace(/([a-z])([A-Z])/g, '$1 $2');

  // Replace space and underscore with dashes
  return str.replace(regex, '-').toLowerCase();

}

答案 9 :(得分:0)

function insert(arr){
    arr = arr.split("");
    for(let i in arr){
      if (/[A-Z]/.test(arr[i])&& i>0){
        arr[i] = "-" + arr[i];
      }
    }
    arr = arr.join("");
    return arr;
  }

function spinalCase(str) {
  
  str = str.split(/\s+|_/);
  str = str.map(item=>insert(item));
  str = str.join("-");
  str = str.toLowerCase();
  return str;
  
}