Domanda

Come posso convertire una stringa in caso di cammello utilizzando JavaScript regex?

EquipmentClass name o Equipment className o equipment class name o Equipment Class Name

dovrebbe diventare tutti:. equipmentClassName

È stato utile?

Soluzione 3

Ho appena finito per fare questo:

String.prototype.toCamelCase = function(str) {
    return str
        .replace(/\s(.)/g, function($1) { return $1.toUpperCase(); })
        .replace(/\s/g, '')
        .replace(/^(.)/, function($1) { return $1.toLowerCase(); });
}

Stavo cercando di evitare il concatenamento insieme multipla sostituire dichiarazioni. Qualcosa in cui avrei $ 1, $ 2, $ 3 nella mia funzione. Ma che tipo di raggruppamento è difficile da capire, e la vostra menzione sui problemi cross browser è qualcosa che non ho mai pensato pure.

Altri suggerimenti

Guardando il codice, è possibile ottenere con solo due chiamate replace:

function camelize(str) {
  return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function(word, index) {
    return index == 0 ? word.toLowerCase() : word.toUpperCase();
  }).replace(/\s+/g, '');
}

camelize("EquipmentClass name");
camelize("Equipment className");
camelize("equipment class name");
camelize("Equipment Class Name");
// all output "equipmentClassName"

Modifica:. o con una singola chiamata replace, catturando gli spazi bianchi anche nella RegExp

function camelize(str) {
  return str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function(match, index) {
    if (+match === 0) return ""; // or if (/\s+/.test(match)) for white spaces
    return index == 0 ? match.toLowerCase() : match.toUpperCase();
  });
}

Se qualcuno sta usando lodash , c'è un _.camelCase() funzione.

_.camelCase('Foo Bar');
// → 'fooBar'

_.camelCase('--foo-bar--');
// → 'fooBar'

_.camelCase('__FOO_BAR__');
// → 'fooBar'

È possibile utilizzare questa soluzione:

function toCamelCase(str){
  return str.split(' ').map(function(word,index){
    // If it is the first word make sure to lowercase all the chars.
    if(index == 0){
      return word.toLowerCase();
    }
    // If it is not the first word only upper case the first char and lowercase the rest.
    return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
  }).join('');
}

Nel caso specifico di Scott mi piacerebbe andare con qualcosa di simile:

String.prototype.toCamelCase = function() {
    return this.replace(/^([A-Z])|\s(\w)/g, function(match, p1, p2, offset) {
        if (p2) return p2.toUpperCase();
        return p1.toLowerCase();        
    });
};

'EquipmentClass name'.toCamelCase()  // -> equipmentClassName
'Equipment className'.toCamelCase()  // -> equipmentClassName
'equipment class name'.toCamelCase() // -> equipmentClassName
'Equipment Class Name'.toCamelCase() // -> equipmentClassName

L'espressione regolare corrisponderà al primo carattere se inizia con una lettera maiuscola, e qualsiasi carattere alfabetico seguendo uno spazio, vale a dire 2 o 3 volte nelle stringhe specificate.

Per vivacizzare l'espressione regolare a /^([A-Z])|[\s-_](\w)/g sarà anche nomi camelize trattino e tipo di sottolineatura.

'hyphen-name-format'.toCamelCase()     // -> hyphenNameFormat
'underscore_name_format'.toCamelCase() // -> underscoreNameFormat
function toCamelCase(str) {
  // Lower cases the string
  return str.toLowerCase()
    // Replaces any - or _ characters with a space 
    .replace( /[-_]+/g, ' ')
    // Removes any non alphanumeric characters 
    .replace( /[^\w\s]/g, '')
    // Uppercases the first character in each group immediately following a space 
    // (delimited by spaces) 
    .replace( / (.)/g, function($1) { return $1.toUpperCase(); })
    // Removes spaces 
    .replace( / /g, '' );
}

I stava cercando di trovare una funzione JavaScript per camelCase una stringa, e voleva assicurarsi che i caratteri speciali sarebbero stati rimossi (e ho avuto difficoltà a capire ciò che alcune delle risposte di cui sopra stavano facendo). Questo si basa sulla risposta c c del giovane, con i commenti aggiunti e la rimozione di $ Peci e l caratteri.

Per ottenere c Amel C ase

ES5

var camalize = function camalize(str) {
    return str.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, function(match, chr)
    {
        return chr.toUpperCase();
    });
}

ES6

var camalize = function camalize(str) {
    return str.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, (m, chr) => chr.toUpperCase());
}

Per ottenere C Amel S entence C ase o P Ascal C ase

var camelSentence = function camelSentence(str) {
    return  (" " + str).toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, function(match, chr)
    {
        return chr.toUpperCase();
    });
}

Nota:
Per quelli di lingua con accenti. COMPRENDONO À-ÖØ-öø-ÿ con l'espressione regolare come segue
.replace(/[^a-zA-ZÀ-ÖØ-öø-ÿ0-9]+(.)/g

Se non è richiesto regexp, si potrebbe desiderare di guardare codice seguente ho fatto molto tempo fa per scintillio :

String.prototype.toUpperCaseFirstChar = function() {
    return this.substr( 0, 1 ).toUpperCase() + this.substr( 1 );
}

String.prototype.toLowerCaseFirstChar = function() {
    return this.substr( 0, 1 ).toLowerCase() + this.substr( 1 );
}

String.prototype.toUpperCaseEachWord = function( delim ) {
    delim = delim ? delim : ' ';
    return this.split( delim ).map( function(v) { return v.toUpperCaseFirstChar() } ).join( delim );
}

String.prototype.toLowerCaseEachWord = function( delim ) {
    delim = delim ? delim : ' ';
    return this.split( delim ).map( function(v) { return v.toLowerCaseFirstChar() } ).join( delim );
}

Non ho fatto alcun test di performance, e le versioni regexp potrebbe o non potrebbe essere più veloce.

Il mio ES6 approccio:

const camelCase = str => {
  let string = str.toLowerCase().replace(/[^A-Za-z0-9]/g, ' ').split(' ')
                  .reduce((result, word) => result + capitalize(word.toLowerCase()))
  return string.charAt(0).toLowerCase() + string.slice(1)
}

const capitalize = str => str.charAt(0).toUpperCase() + str.toLowerCase().slice(1)

let baz = 'foo bar'
let camel = camelCase(baz)
console.log(camel)  // "fooBar"
camelCase('foo bar')  // "fooBar"
camelCase('FOO BAR')  // "fooBar"
camelCase('x nN foo bar')  // "xNnFooBar"
camelCase('!--foo-¿?-bar--121-**%')  // "fooBar121"

lodash può fare il trucco sicuro e ben:

var _ = require('lodash');
var result = _.camelCase('toto-ce héros') 
// result now contains "totoCeHeros"

Anche se lodash può essere una libreria di "grande" (~ 4kB), contiene un sacco di funzioni che che normalmente si usa per un frammento, o costruire da soli.

Ecco un uno di linea facendo il lavoro:

const camelCaseIt = string => string.toLowerCase().trim().split(/[.\-_\s]/g).reduce((string, word) => string + word[0].toUpperCase() + word.slice(1));

Si divide la stringa in minuscolo in base all'elenco dei caratteri forniti nella [.\-_\s] RegExp (aggiungere più all'interno del []!) E restituisce una matrice di parola. Poi, si riduce la matrice di stringhe per una stringa concatenata di parole con prime lettere maiuscolo. Poiché il ridurre ha alcun valore iniziale, inizierà maiuscolo prime lettere che iniziano con la seconda parola.

Se si desidera PascalCase, è sufficiente aggiungere un primo ,'') stringa vuota al metodo ridurre.

return "hello world".toLowerCase().replace(/(?:(^.)|(\s+.))/g, function(match) {
    return match.charAt(match.length-1).toUpperCase();
}); // HelloWorld

dopo @ approccio leggibile di Scott, un po 'di messa a punto

// convert any string to camelCase
var toCamelCase = function(str) {
  return str.toLowerCase()
    .replace( /['"]/g, '' )
    .replace( /\W+/g, ' ' )
    .replace( / (.)/g, function($1) { return $1.toUpperCase(); })
    .replace( / /g, '' );
}

Tutte le 14 permutazioni di seguito producono lo stesso risultato di "equipmentClassName".

String.prototype.toCamelCase = function() {
  return this.replace(/[^a-z ]/ig, '')  // Replace everything but letters and spaces.
    .replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, // Find non-words, uppercase letters, leading-word letters, and multiple spaces.
      function(match, index) {
        return +match === 0 ? "" : match[index === 0 ? 'toLowerCase' : 'toUpperCase']();
      });
}

String.toCamelCase = function(str) {
  return str.toCamelCase();
}

var testCases = [
  "equipment class name",
  "equipment class Name",
  "equipment Class name",
  "equipment Class Name",
  "Equipment class name",
  "Equipment class Name",
  "Equipment Class name",
  "Equipment Class Name",
  "equipment className",
  "equipment ClassName",
  "Equipment ClassName",
  "equipmentClass name",
  "equipmentClass Name",
  "EquipmentClass Name"
];

for (var i = 0; i < testCases.length; i++) {
  console.log(testCases[i].toCamelCase());
};

è possibile utilizzare questa soluzione:

String.prototype.toCamelCase = function(){
  return this.replace(/\s(\w)/ig, function(all, letter){return letter.toUpperCase();})
             .replace(/(^\w)/, function($1){return $1.toLowerCase()});
};

console.log('Equipment className'.toCamelCase());

po 'modificato la risposta di Scott:

toCamelCase = (string) ->
  string
    .replace /[\s|_|-](.)/g, ($1) -> $1.toUpperCase()
    .replace /[\s|_|-]/g, ''
    .replace /^(.)/, ($1) -> $1.toLowerCase()

ora sostituisce '-'. E '_' troppo

Non è la mia soluzione:

const toCamelWord = (word, idx) =>
  idx === 0 ?
  word.toLowerCase() :
  word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();

const toCamelCase = text =>
  text
  .split(/[_-\s]+/)
  .map(toCamelWord)
  .join("");

console.log(toCamelCase('User ID'))

Questo metodo sembra a sovraperformare la maggior parte delle risposte su qui, è un po 'però hacky, non sostituisce, senza regex, semplicemente costruendo una nuova stringa che è camelCase.

String.prototype.camelCase = function(){
    var newString = '';
    var lastEditedIndex;
    for (var i = 0; i < this.length; i++){
        if(this[i] == ' ' || this[i] == '-' || this[i] == '_'){
            newString += this[i+1].toUpperCase();
            lastEditedIndex = i+1;
        }
        else if(lastEditedIndex !== i) newString += this[i].toLowerCase();
    }
    return newString;
}

Questa si basa sulla risposta da CMS, eliminando tutti i caratteri non alfabetici tra di sottolineatura, che \w non rimuove.

function toLowerCamelCase(str) {
    return str.replace(/[^A-Za-z0-9]/g, ' ').replace(/^\w|[A-Z]|\b\w|\s+/g, function (match, index) {
        if (+match === 0 || match === '-' || match === '.' ) {
            return ""; // or if (/\s+/.test(match)) for white spaces
        }
        return index === 0 ? match.toLowerCase() : match.toUpperCase();
    });
}

toLowerCamelCase("EquipmentClass name");
toLowerCamelCase("Equipment className");
toLowerCamelCase("equipment class name");
toLowerCamelCase("Equipment Class Name");
toLowerCamelCase("Equipment-Class-Name");
toLowerCamelCase("Equipment_Class_Name");
toLowerCamelCase("Equipment.Class.Name");
toLowerCamelCase("Equipment/Class/Name");
// All output e

caso cammello superiore ( "TestString") per abbassare caso di cammello ( "testString") senza l'utilizzo di espressioni regolari (diciamocelo, regex è il male):

'TestString'.split('').reduce((t, v, k) => t + (k === 0 ? v.toLowerCase() : v), '');

Ho finito per lavorazione una soluzione un po 'più aggressivo:

function toCamelCase(str) {
  const [first, ...acc] = str.replace(/[^\w\d]/g, ' ').split(/\s+/);
  return first.toLowerCase() + acc.map(x => x.charAt(0).toUpperCase() 
    + x.slice(1).toLowerCase()).join('');
}

Questo, sopra, rimuoverà tutti i caratteri non alfanumerici e parti minuscole di parole che altrimenti resterebbero maiuscolo, per esempio.

  • Size (comparative) => sizeComparative
  • GDP (official exchange rate) => gdpOfficialExchangeRate
  • hello => hello
function convertStringToCamelCase(str){
    return str.split(' ').map(function(item, index){
        return index !== 0 
            ? item.charAt(0).toUpperCase() + item.substr(1) 
            : item.charAt(0).toLowerCase() + item.substr(1);
    }).join('');
}      

Perché questa domanda necessaria l'ennesima risposta ...

Ho provato molte delle soluzioni precedenti, e tutti avevano un difetto o un altro. Alcuni non rimuovere la punteggiatura; Alcuni non gestire casi con numeri; alcuni non hanno gestire più segni di interpunzione di fila.

Nessuno di loro ha gestito una stringa come a1 2b. Non c'è nessuna convenzione esplicitamente definito per questo caso, ma qualche altro StackOverflow domande suggerito che separa i numeri con un carattere di sottolineatura.

Dubito che questa è la risposta più performante (tre regex passa attraverso la stringa, piuttosto che uno o due), ma passa tutti i test che posso pensare. Per essere onesti, però, davvero non riesco a immaginare un caso in cui si sta facendo tante conversioni cammello caso che le prestazioni avrebbe avuto importanza.

(ho aggiunto questo come un NPM pacchetto . Esso include anche un optional parametro booleano per tornare Pascal caso invece di Camel Case.)

const underscoreRegex = /(?:[^\w\s]|_)+/g,
    sandwichNumberRegex = /(\d)\s+(?=\d)/g,
    camelCaseRegex = /(?:^\s*\w|\b\w|\W+)/g;

String.prototype.toCamelCase = function() {
    if (/^\s*_[\s_]*$/g.test(this)) {
        return '_';
    }

    return this.replace(underscoreRegex, ' ')
        .replace(sandwichNumberRegex, '$1_')
        .replace(camelCaseRegex, function(match, index) {
            if (/^\W+$/.test(match)) {
                return '';
            }

            return index == 0 ? match.trimLeft().toLowerCase() : match.toUpperCase();
        });
}

Casi di test (Jest)

test('Basic strings', () => {
    expect(''.toCamelCase()).toBe('');
    expect('A B C'.toCamelCase()).toBe('aBC');
    expect('aB c'.toCamelCase()).toBe('aBC');
    expect('abc      def'.toCamelCase()).toBe('abcDef');
    expect('abc__ _ _def'.toCamelCase()).toBe('abcDef');
    expect('abc__ _ d_ e _ _fg'.toCamelCase()).toBe('abcDEFg');
});

test('Basic strings with punctuation', () => {
    expect(`a'b--d -- f.h`.toCamelCase()).toBe('aBDFH');
    expect(`...a...def`.toCamelCase()).toBe('aDef');
});

test('Strings with numbers', () => {
    expect('12 3 4 5'.toCamelCase()).toBe('12_3_4_5');
    expect('12 3 abc'.toCamelCase()).toBe('12_3Abc');
    expect('ab2c'.toCamelCase()).toBe('ab2c');
    expect('1abc'.toCamelCase()).toBe('1abc');
    expect('1Abc'.toCamelCase()).toBe('1Abc');
    expect('abc 2def'.toCamelCase()).toBe('abc2def');
    expect('abc-2def'.toCamelCase()).toBe('abc2def');
    expect('abc_2def'.toCamelCase()).toBe('abc2def');
    expect('abc1_2def'.toCamelCase()).toBe('abc1_2def');
    expect('abc1 2def'.toCamelCase()).toBe('abc1_2def');
    expect('abc1 2   3def'.toCamelCase()).toBe('abc1_2_3def');
});

test('Oddball cases', () => {
    expect('_'.toCamelCase()).toBe('_');
    expect('__'.toCamelCase()).toBe('_');
    expect('_ _'.toCamelCase()).toBe('_');
    expect('\t_ _\n'.toCamelCase()).toBe('_');
    expect('_a_'.toCamelCase()).toBe('a');
    expect('\''.toCamelCase()).toBe('');
    expect(`\tab\tcd`.toCamelCase()).toBe('abCd');
    expect(`
ab\tcd\r

-_

|'ef`.toCamelCase()).toBe(`abCdEf`);
});

Ecco il mio consiglio:

function toCamelCase(string) {
  return `${string}`
    .replace(new RegExp(/[-_]+/, 'g'), ' ')
    .replace(new RegExp(/[^\w\s]/, 'g'), '')
    .replace(
      new RegExp(/\s+(.)(\w+)/, 'g'),
      ($1, $2, $3) => `${$2.toUpperCase() + $3.toLowerCase()}`
    )
    .replace(new RegExp(/\s/, 'g'), '')
    .replace(new RegExp(/\w/), s => s.toLowerCase());
}

o

String.prototype.toCamelCase = function() {
  return this
    .replace(new RegExp(/[-_]+/, 'g'), ' ')
    .replace(new RegExp(/[^\w\s]/, 'g'), '')
    .replace(
      new RegExp(/\s+(.)(\w+)/, 'g'),
      ($1, $2, $3) => `${$2.toUpperCase() + $3.toLowerCase()}`
    )
    .replace(new RegExp(/\s/, 'g'), '')
    .replace(new RegExp(/\w/), s => s.toLowerCase());
};

Casi di test:

describe('String to camel case', function() {
  it('should return a camel cased string', function() {
    chai.assert.equal(toCamelCase('foo bar'), 'fooBar');
    chai.assert.equal(toCamelCase('Foo Bar'), 'fooBar');
    chai.assert.equal(toCamelCase('fooBar'), 'fooBar');
    chai.assert.equal(toCamelCase('FooBar'), 'fooBar');
    chai.assert.equal(toCamelCase('--foo-bar--'), 'fooBar');
    chai.assert.equal(toCamelCase('__FOO_BAR__'), 'fooBar');
    chai.assert.equal(toCamelCase('!--foo-¿?-bar--121-**%'), 'fooBar121');
  });
});

So che questa è una risposta vecchia, ma questo gestisce sia gli spazi bianchi e _ (lodash)

function toCamelCase(s){
    return s
          .replace(/_/g, " ")
          .replace(/\s(.)/g, function($1) { return $1.toUpperCase(); })
          .replace(/\s/g, '')
          .replace(/^(.)/, function($1) { return $1.toLowerCase(); });
}

console.log(toCamelCase("Hello world");
console.log(toCamelCase("Hello_world");

// Both print "helloWorld"

approccio di base sarebbe quella di dividere la stringa con una regex corrispondenza maiuscole o spazi. Poi devi incollare i pezzi di nuovo insieme. Trucco sarà trattare con i vari modi si divide regex sono rotto / strani tutti i browser. C'è una biblioteca o qualcosa che qualcuno ha scritto per risolvere questi problemi; Cercherò di esso.

ecco il link: http://blog.stevenlevithan.com/archives/cross -browser-split

Modifica : Ora lavora in IE8 senza cambiamenti.

Modifica : ero in minoranza su ciò che è in realtà camelCase (protagonista minuscolo vs. maiuscolo.). La comunità in generale crede che un minuscolo leader è caso cammello e un capitale importante è caso pascal. Ho creato due funzioni che utilizzano solo i modelli di espressioni regolari. :) Quindi usiamo un vocabolario unificata ho cambiato la mia posizione in modo che corrisponda la maggioranza.


Tutto quello che hai bisogno è una singola espressione regolare in entrambi i casi:

var camel = " THIS is camel case "
camel = $.trim(camel)
    .replace(/[^A-Za-z]/g,' ') /* clean up non-letter characters */
    .replace(/(.)/g, function(a, l) { return l.toLowerCase(); })
    .replace(/(\s.)/g, function(a, l) { return l.toUpperCase(); })
    .replace(/[^A-Za-z\u00C0-\u00ff]/g,'');
// Returns "thisIsCamelCase"

o

var pascal = " this IS pascal case "
pascal = $.trim(pascal)
  .replace(/[^A-Za-z]/g,' ') /* clean up non-letter characters */
  .replace(/(.)/g, function(a, l) { return l.toLowerCase(); })
  .replace(/(^.|\s.)/g, function(a, l) { return l.toUpperCase(); })
  .replace(/[^A-Za-z\u00C0-\u00ff]/g,'');
// Returns "ThisIsPascalCase"

In funzioni: si noterà che in queste funzioni Sostituisci è lo swapping qualsiasi a-z non con uno spazio vs una stringa vuota. Questo è quello di creare confini di parola per la capitalizzazione. "Ciao-MY # mondo" -> "HelloMyWorld"

// remove \u00C0-\u00ff] if you do not want the extended letters like é
function toCamelCase(str) {
    var retVal = '';

    retVal = $.trim(str)
      .replace(/[^A-Za-z]/g, ' ') /* clean up non-letter characters */
      .replace(/(.)/g, function (a, l) { return l.toLowerCase(); })
      .replace(/(\s.)/g, function (a, l) { return l.toUpperCase(); })
      .replace(/[^A-Za-z\u00C0-\u00ff]/g, '');

    return retVal
}

function toPascalCase(str) {
    var retVal = '';

    retVal = $.trim(str)
      .replace(/[^A-Za-z]/g, ' ') /* clean up non-letter characters */
      .replace(/(.)/g, function (a, l) { return l.toLowerCase(); })
      .replace(/(^.|\s.)/g, function (a, l) { return l.toUpperCase(); })
      .replace(/[^A-Za-z\u00C0-\u00ff]/g, '');

    return retVal
}

Note:

  • I sinistra A-Za-z vs aggiungendo la bandiera caso insensibilità (i) per il modello (/ [^ A-Z] / IG) per migliorare la leggibilità.
  • Questo funziona in IE8 (srsly, che usa più IE8.) Utilizzando la (F12) strumenti di sviluppo ho testato in IE11, IE10, IE9, IE8, IE7 e IE5. Funziona in tutte le modalità di documenti.
  • Questo correttamente caso la prima lettera di stringhe che iniziano con o senza spazi.

Godetevi

Credo che questo dovrebbe funzionare ..

function cammelCase(str){
    let arr = str.split(' ');
    let words = arr.filter(v=>v!='');
    words.forEach((w, i)=>{
        words[i] = w.replace(/\w\S*/g, function(txt){
            return txt.charAt(0).toUpperCase() + txt.substr(1);
        });
    });
    return words.join('');
}

Non utilizzare String.prototype.toCamelCase () perché String.prototypes sono di sola lettura, la maggior parte dei compilatori js vi darà questo avvertimento.

Come me, chi sa che la stringa sarà sempre contiene un solo spazio può utilizzare un approccio più semplice:

let name = 'test string';

let pieces = name.split(' ');

pieces = pieces.map((word, index) => word.charAt(0)[index===0 ? 'toLowerCase' :'toUpperCase']() + word.toLowerCase().slice(1));

return pieces.join('');

Buona giornata. :)

Un modo super facile, utilizzando la libreria turboCommons:

npm install turbocommons-es5

<script src="turbocommons-es5/turbocommons-es5.js"></script>

<script>
    var StringUtils = org_turbocommons.StringUtils;
    console.log(StringUtils.formatCase('EquipmentClass', StringUtils.FORMAT_LOWER_CAMEL_CASE));
    console.log(StringUtils.formatCase('Equipment className', StringUtils.FORMAT_LOWER_CAMEL_CASE));
    console.log(StringUtils.formatCase('equipment class name', StringUtils.FORMAT_LOWER_CAMEL_CASE));
    console.log(StringUtils.formatCase('Equipment Class Name', StringUtils.FORMAT_LOWER_CAMEL_CASE));
</script>

È inoltre possibile utilizzare StringUtils.FORMAT_CAMEL_CASE e StringUtils.FORMAT_UPPER_CAMEL_CASE per generare prime variazioni lettera caso.

Più informazioni qui:

stringa Converti CamelCase, UpperCamelCase o lowerCamelCase

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top