Konwertuj myślniki do wielbłąda (camelCase)

Za pomocą regex (zakładam) lub innej metody, Jak mogę przekonwertować takie rzeczy jak:

marker-image lub my-example-setting do markerImage lub myExampleSetting.

Myślałem o podzieleniu przez -, a następnie przekonwertowaniu indeksu tego hypen +1 na wielkie litery. Ale wydaje się dość brudne i miał nadzieję na pomoc z regex, które mogłyby uczynić kod czystsze.

Nie jQuery...

Author: Oscar Godson, 2011-07-12

14 answers

Spróbuj tego:

var camelCased = myString.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); });

Wyrażenie regularne będzie pasować do -i w marker-image i przechwytuje tylko i. Jest to następnie zapisywane wielkimi literami w funkcji zwrotnej i zastępowane.

 272
Author: Paolo Moretti,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-04 11:53:29

Jest to jedno z najlepszych narzędzi, które oferuje Lodash, jeśli jesteś oświecony i masz je w swoim projekcie.

var str = 'my-hyphen-string';
str = _.camelCase(str);
// results in 'myHyphenString'
 46
Author: ShadeTreeDeveloper,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-07 13:21:41

Możesz uzyskać hypen i następny znak i zastąpić go wielką wersją znaku:

var str="marker-image-test";
str.replace(/-([a-z])/g, function (m, w) {
    return w.toUpperCase();
});
 14
Author: mck89,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-07-12 07:49:42

Oto moja wersja funkcji camelCase:

var camelCase = (function () {
    var DEFAULT_REGEX = /[-_]+(.)?/g;

    function toUpper(match, group1) {
        return group1 ? group1.toUpperCase() : '';
    }
    return function (str, delimiters) {
        return str.replace(delimiters ? new RegExp('[' + delimiters + ']+(.)?', 'g') : DEFAULT_REGEX, toUpper);
    };
})();

Obsługuje wszystkie następujące przypadki krawędzi:

  • domyślnie dba o podkreślniki i myślniki (konfigurowalne za pomocą drugiego parametru)
  • łańcuch znaków unicode
  • ciąg kończący się myślnikami lub podkreśleniem
  • łańcuch, który ma kolejne myślniki lub podkreślniki

Oto link do testów na żywo: http://jsfiddle.net/avKzf/2/

Oto wyniki z testy:

  • input: "ab-cd-ef", result: "abCdEf"
  • input: "ab-cd-ef -", result: "abCdEf"
  • input: "ab-cd-ef--", result: "abCdEf"
  • input: "ab-cd--ef--", result: "abCdEf"
  • input: "--ab-cd--ef--", result: "AbCdEf"
  • input: "--ab-cd - _ _ - ef--", result: "AbCdEf"

Zauważ, że ciągi rozpoczynające się od ograniczników będą skutkować wielką literą na początku. Jeśli nie tego się spodziewasz, zawsze możesz użyć lcfirst. Oto mój lcfirst jeśli potrzebujesz:

function lcfirst(str) {
    return str && str.charAt(0).toLowerCase() + str.substring(1);
}
 13
Author: Joon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-01 09:22:01

To nie krzyczy dla mnie. OsobiĹ "cie staram siÄ ™ unikaÄ ‡ wyraĺźeĺ" regularnych, gdy wystarczajÄ ... proste metody string i array:

let upFirst = word => 
  word[0].toUpperCase() + word.toLowerCase().slice(1)

let camelize = text => {
  let words = text.split(/[-_]/g) // ok one simple regexp.
  return words[0].toLowerCase() + words.slice(1).map(upFirst)
}

camelize('marker-image') // markerImage
 4
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-14 19:38:23

Oto kolejna opcja, która łączy kilka odpowiedzi tutaj i sprawia, że metoda na łańcuchu:

if (typeof String.prototype.toCamel !== 'function') {
  String.prototype.toCamel = function(){
    return this.replace(/[-_]([a-z])/g, function (g) { return g[1].toUpperCase(); })
  };
}

Używane w ten sposób:

'quick_brown'.toCamel(); // quickBrown
'quick-brown'.toCamel(); // quickBrown
 1
Author: John Naegle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-05 15:08:24
// Turn the dash separated variable name into camelCase.
str = str.replace(/\b-([a-z])/g, (_, char) => char.toUpperCase());
 1
Author: alex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-12-17 10:53:42

Możesz użyć camelcase z NPM.

npm install --save camelcase

const camelCase = require('camelcase');
camelCase('marker-image'); // => 'markerImage';
camelCase('my-example-setting'); // => 'myExampleSetting';
 1
Author: Lanil Marasinghe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-01-04 11:44:44

Kolejne ujęcie.

Używane, gdy...

var string = "hyphen-delimited-to-camel-case"
or
var string = "snake_case_to_camel_case"


function toCamelCase( string ){
  return string.toLowerCase().replace(/(_|-)([a-z])/g, toUpperCase );
}

function toUpperCase( string ){
  return string[1].toUpperCase();
}

Output: hyphenDelimitedToCamelCase
 0
Author: SoEzPz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-17 17:40:40

Jest również możliwe użycie indexOf z rekurencją dla tego zadania.

input some-foo_sd_dsd-weqe
output someFooSdDsdWeqe

Comparison ::: measure execution time for two different scripts:

$ node camelCased.js
someFooSdDsdWeqe
test1: 2.986ms
someFooSdDsdWeqe
test2: 0.231ms

Kod:

console.time('test1');
function camelCased (str) {

        function check(symb){

            let idxOf = str.indexOf(symb);
            if (idxOf === -1) {
                return str;
            }

            let letter = str[idxOf+1].toUpperCase();
            str = str.replace(str.substring(idxOf+1,idxOf+2), '');
            str = str.split(symb).join(idxOf !== -1 ? letter : '');

            return camelCased(str);
        }       

        return check('_') && check('-');

    }

console.log(camelCased ('some-foo_sd_dsd-weqe'));
console.timeEnd('test1');



console.time('test2');

    function camelCased (myString){
     return myString.replace(/(-|\_)([a-z])/g, function (g) { return  g[1].toUpperCase(); });
   }


console.log(camelCased ('some-foo_sd_dsd-weqe'));
console.timeEnd('test2');
 0
Author: Anja Ishmukhametova,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-11 10:32:24

Tylko wersja z flagą, dla pętli i bez Regex:

function camelCase(dash) { 

  var camel = false;
  var str = dash;
  var camelString = '';

  for(var i = 0; i < str.length; i++){
    if(str.charAt(i) === '-'){
      camel = true;

    } else if(camel) {
      camelString += str.charAt(i).toUpperCase();
      camel = false;
    } else {
      camelString += str.charAt(i);
    }
  } 
  return camelString;
}
 0
Author: Hunter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-30 18:30:25

Oto moja implementacja (tylko po to, aby brudzić ręce)

/**
 * kebab-case to UpperCamelCase
 * @param {String} string
 * @return {String}
 */
function toUpperCamelCase(string) {
  return string
    .toLowerCase()
    .split('-')
    .map(it => it.charAt(0).toUpperCase() + it.substr(1))
    .join('');
}
 0
Author: D.Dimitrioglo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-10-01 17:45:49

Użyj tego, jeśli pozwolisz liczbom w Twoim łańcuchu.

Oczywiście części zaczynające się od liczby nie będą pisane wielkimi literami, ale może to być przydatne w niektórych sytuacjach.

function fromHyphenToCamelCase(str) {
  return str.replace(/-([a-z0-9])/g, (g) => g[1].toUpperCase())
}

function fromHyphenToCamelCase(str) {
  return str.replace(/-([a-z0-9])/g, (g) => g[1].toUpperCase())
}

const str1 = "category-123";
const str2 = "111-222";
const str3 = "a1a-b2b";
const str4 = "aaa-2bb";

console.log(`${str1} => ${fromHyphenToCamelCase(str1)}`);
console.log(`${str2} => ${fromHyphenToCamelCase(str2)}`);
console.log(`${str3} => ${fromHyphenToCamelCase(str3)}`);
console.log(`${str4} => ${fromHyphenToCamelCase(str4)}`);
 0
Author: cbdeveloper,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-11 13:47:05

Użycie String's replace() metoda z wyrażeniem regularnym i funkcją zastępczą.

Na przykład:

'uno-due-tre'.replace(/-./g, (m) => m[1].toUpperCase()) // --> 'unoDueTre'

Wyjaśnienie:

  • 'uno-due-tre' jest łańcuchem (wejściowym), który chcesz przekonwertować na wielkość wielbłąda.
  • /-./g (pierwszy argument przekazany do replace()) jest wyrażeniem regularnym literalnym.
    • '-.' (pomiędzy ukośnikami) jest wzorem. Pasuje do pojedynczego znaku '-', po którym następuje Dowolna pojedynczy znak. Tak więc dla ciągu 'uno-due-tre', wzór '-.' pasuje do '-d' i '-t'.
    • 'g' (po ukośniku zamykającym) jest flagą. Oznacza "globalny" i mówi replace() aby wykonać globalne wyszukiwanie i zastąpić, czyli zastąpić wszystkie mecze, a nie tylko pierwszy.
  • (m) => m[1].toUpperCase() (drugi argument przeszedł do replace()) jest funkcją zastępczą. Nazywa się to raz na każdy mecz. Każdy dopasowany podłańcuch jest zastępowany przez łańcuch ten funkcja zwraca. m (pierwszy argument tej funkcji) przedstawia dopasowany podłańcuch. Funkcja zwraca drugi znak m pisany wielkimi literami. Jeśli więc m jest '-d', funkcja ta zwraca 'D'.
  • 'unoDueTre' jest nowym (wyjściowym) łańcuchem zwracanym przez replace(). Ciąg wejściowy pozostaje bez zmian.
 0
Author: ma11hew28,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-01-22 03:52:22