Convert sentence or word camelCase to spinal register

I am trying to convert both the case of a sentence and the case of a camel into a spinal register.

I can change the case of a camel by adding a space in front of each capital letter, but when I apply it to sentences with capital letters after spaces, I get an extra spacing.

Here is my function:

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
+4
source share
5 answers

Get lodash, in particular https://lodash.com/docs#kebabCase .

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

Instead:

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

Try:

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

, . , this spinal.

, "-$1", .

0
source
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 str.replace(/([A-Z])/g, ' $1')for decomposition on a camel case you should use str.replace(/([a-z](?=[A-Z]))/g, '$1 ')one that will highlight every word regardless of case.

0
source

Here is my solution, maybe you will find it a good guide:

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

Source: https://habr.com/ru/post/1628571/


All Articles