Convert sentence or camelCase word to spinal-case

时间:2016-02-12 20:38:24

标签: javascript regex

I am trying to convert both sentence case and camel case to spinal case.

I am able to change camel case to by adding a space before every capital letter, but when I apply it to sentences with capital letters after spaces, I get extra spacing.

Here is my function so far :

#your_specific_ID_name .image_myclass_image {
   background-position: 0px 0px;
   height: 'the height of your image';
   width: 'the width of your image';
   font-size: 0;
}

5 个答案:

答案 0 :(得分:2)

Get lodash, specifically, https://lodash.com/docs#kebabCase.

^[ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ]\d[ABCEGHJKLMNPRSTVWXYZ]\d$

答案 1 :(得分:1)

Instead of:

Director::getInstance()->getRunningScene()->addChild(...)

Try:

var noCamel = str.replace(/([A-Z])/g, ' $1');

答案 2 :(得分:0)

It's because you're replacing all capital letters with a space and its lowercase letter. So in your sentence, you're getting two spaces before import re def tokenise(txt): # Expand "'ve" txt = re.sub(r"(?i)(\w)'ve\b", r'\1 have', txt) # Separate punctuation from words txt = re.sub(r'\b', ' ', txt) # Remove isolated, single-character punctuation, # and articles (a, an, the) txt = re.sub(r'(^|\s)([.;:]|[Aa]n|a|[Tt]he)($|\s)', r'\1\3', txt) # Split into non-empty strings return filter(bool, re.split(r'\s+', txt)) # Example use txt = "I've got an A mark!!! Such a relief... I should've partied more." words = tokenise(txt) print (','.join(words)) and this.

What you can do is replace all uppercase letters with spinal and then just remove all spaces from the string.

答案 3 :(得分:0)

Object {nmech: "3.00", nelect: "3.00", nplant: "0.00", ncivil: "55.00"}

Instead of function spinalCase(str) { var noCamel = str.replace(/([a-z](?=[A-Z]))/g, '$1 ') var newStr = noCamel.replace(/\s|_/g, "-"); return newStr.toLowerCase(); } spinalCase("makeThisSpinal"); //returns make-this-spinal spinalCase("Make This Spinal"); //returns -make-this-spinal for the camel case split, you should use str.replace(/([A-Z])/g, ' $1') which will space out each word regardless of case.

答案 4 :(得分:0)

这是我的解决方案,也许你会发现它很好的参考:

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;
}