Búsqueda de sitios web

javascript - Convertir una cadena con espacios en camel case


¿Cómo puedo convertir una cadena a camel case usando regex en JavaScript?

NombreDeClaseDeEquipo o ClaseDeEquipoNombre o nombre de la clase de equipo o Nombre de la Clase de Equipo

deberían convertirse todos en: equipmentClassName.

Respuesta #1

Mirando tu código, puedes lograrlo con solo dos llamadas a 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, '');
}

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

Editar: O en con una sola llamada a replace, capturando también los espacios en blanco en el 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();
  });
}

Respuesta #2

Si alguien está usando lodash, hay una función _.camelCase().

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

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

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

Respuesta #3

Para obtener camelCase

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

Para obtener camelCase o PascalCase

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

Nota:
Para aquellos idiomas con acentos. Incluya À-ÖØ-öø-ÿ en la expresión regular de la siguiente manera
.replace(/[^a-zA-ZÀ-ÖØ-öø-ÿ0-9]+(.)/g Esto es solo para un idioma. Para otro idioma, debe buscar y encontrar

Respuesta #4

Yo simplemente terminé haciendo esto:

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

Estaba tratando de evitar encadenar múltiples instrucciones replace. Algo donde tendría $1, $2, $3 en mi función. Pero ese tipo de agrupación es difícil de entender, y tu mención sobre problemas entre distintos navegadores es algo en lo que nunca había pensado también.

Respuesta #5

Puedes usar esta solución:

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('');
}

Respuesta #6

Ejemplo confiable y de alto rendimiento:

function camelize(text) {
    const a = text.toLowerCase()
        .replace(/[-_\s.]+(.)?/g, (_, c) => c ? c.toUpperCase() : '');
    return a.substring(0, 1).toLowerCase() + a.substring(1);
}

Caracteres que cambian de mayúscula a minúscula:

  • guion -
  • guion bajo _
  • punto .
  • espacio

Respuesta #7

En el caso específico de Scott, yo iría con algo como:

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

El regex coincidirá con el primer carácter si comienza con una letra mayúscula, y con cualquier carácter alfabético que siga a un espacio, es decir, 2 o 3 veces en las cadenas especificadas.

Al mejorar la expresión regular a /^([A-Z])|[\s-_](\w)/g, también se camelizarán los nombres con guiones y guiones bajos.

'hyphen-name-format'.toCamelCase()     // -> hyphenNameFormat
'underscore_name_format'.toCamelCase() // -> underscoreNameFormat

Respuesta #8

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, '' );
}

Estaba tratando de encontrar una función de JavaScript para camelCase una cadena, y quería asegurarme de que los caracteres especiales fueran eliminados (y tuve problemas para entender lo que algunas de las respuestas anteriores estaban haciendo). Esto se basa en la respuesta de c c young, con comentarios añadidos y la eliminación de caracteres $peci&l.

Respuesta #9

Si no se requiere regexp, quizá quieras echar un vistazo al siguiente código que hice hace mucho tiempo para Twinkle:

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

No he realizado ninguna prueba de rendimiento, y las versiones con expresiones regulares podrían ser más rápidas o no.

Respuesta #10

Para crear eficazmente una función que convierta el formato de una cadena a camel-case, la función también necesitará convertir cada cadena a minúsculas primero, antes de transformar el formato del primer carácter de las cadenas que no son la primera a una letra mayúscula.

Mi cadena de ejemplo es:

"text That I WaNt to make cAMEL case"

Muchas otras soluciones proporcionadas a esta pregunta devuelven esto:

"textThatIWaNtToMakeCAMELCase"

Lo que creo que sería el resultado deseado sería esto, sin embargo, donde todos los caracteres en mayúscula en medio de la cadena se transforman primero a minúscula:

"textThatIWantToMakeCamelCase"

Esto se puede hacer SIN usar ninguna llamada al método replace(), utilizando los métodos String.prototype.split(), Array.prototype.map() y Array.prototype.join():

≤ Versión ES5

function makeCamelCase(str) {
  return str
    .split(' ')
    .map((e,i) => i
      ? e.charAt(0).toUpperCase() + e.slice(1).toLowerCase()
      : e.toLowerCase()
    )
    .join('')
}

makeCamelCase("text That I WaNt to make cAMEL case")
// -> "textThatIWantToMakeCamelCase" ✅

Desglosaré lo que hace cada línea y luego proporcionaré la misma solución en otros dos formatos: ES6 y como un método String.prototype, aunque aconsejaría no extender directamente los prototipos incorporados de JavaScript de esta manera.

Explicador

function makeCamelCase(str) {
  return str
    // split string into array of different words by splitting at spaces
    .split(' ')
    // map array of words into two different cases, one for the first word (`i == false`) and one for all other words in the array (where `i == true`). `i` is a parameter that denotes the current index of the array item being evaluated. Because indexes start at `0` and `0` is a "falsy" value, we can use the false/else case of this ternary expression to match the first string where `i === 0`.
    .map((e,i) => i
      // for all non-first words, use a capitalized form of the first character + the lowercase version of the rest of the word (excluding the first character using the slice() method)
      ? e.charAt(0).toUpperCase() + e.slice(1).toLowerCase()
      // for the first word, we convert the entire word to lowercase
      : e.toLowerCase()
    )
    // finally, we join the different strings back together into a single string without spaces, our camel-cased string
    .join('')
}

makeCamelCase("text That I WaNt to make cAMEL case")
// -> "textThatIWantToMakeCamelCase" ✅

Versión condensada ES6+ (en una línea)

const makeCamelCase = str => str.split(' ').map((e,i) => i ? e.charAt(0).toUpperCase() + e.slice(1).toLowerCase() : e.toLowerCase()).join('')

makeCamelCase("text That I WaNt to make cAMEL case")
// -> "textThatIWantToMakeCamelCase" ✅

Versión del método String.prototype

String.prototype.toCamelCase = function() {
  return this
    .split(' ')
    .map((e,i) => i
      ? e.charAt(0).toUpperCase() + e.slice(1).toLowerCase()
      : e.toLowerCase()
    )
    .join('')
}

"text That I WaNt to make cAMEL case".toCamelCase()
// -> "textThatIWantToMakeCamelCase" ✅

Artículos relacionados