简体   繁体   中英

Convert sentence or camelCase word to spinal-case

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 :

function spinalCase(str) {
    var noCamel = str.replace(/([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

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

_.kebabCase('makeThisSpinal') // make-this-spinal
_.kebabCase('Even Sentences Work') // even-sentences-work

Instead of:

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

Try:

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

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 this and spinal .

What you can do is replace all uppercase letters with "-$1" and then just remove all spaces from the string.

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

Instead of str.replace(/([AZ])/g, ' $1') for the camel case split, you should use str.replace(/([az](?=[AZ]))/g, '$1 ') which will space out each word regardless of case.

Here's my solution, perhaps you will find it good reference:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM