将任何字符串转换为驼峰大小写

Sco*_*ach 145 javascript regex camelcasing

如何使用javascript正则表达式将字符串转换为驼峰大小写?

EquipmentClass name或者 Equipment classNameequipment class nameEquipment Class Name

应该都成为:equipmentClassName.

CMS*_*CMS 208

查看代码,只需两次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"
Run Code Online (Sandbox Code Playgroud)

编辑:或者只需一次replace调用,也可以捕获白色空格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();
  });
}
Run Code Online (Sandbox Code Playgroud)

  • 伟大的代码,它最终赢得了https://jsperf.com/js-camelcase/5.注意提供一个可以处理(删除)非alpha字符的版本?`camelize("让我们去做!")==="让我们这么做!"`**悲伤的脸**.我会尝试自己,但我担心我会添加另一个替换. (4认同)
  • 虽然这不是示例询问的情况,但您可能会看到的另一个常见输入是“设备类名称”,对此方法失败。 (4认同)
  • 对于我的ES2015 +朋友:基于以上代码的一根衬垫。`const toCamelCase =(str)=> str.replace(/(?:^ \ w | [AZ] | \ b \ w)/ g,(ltr,idx)=> idx === 0?ltr.toLowerCase( ):ltr.toUpperCase())。replace(/ \ s + / g,'');` (3认同)
  • ..因为非alpha不应该影响这种情况,我不确定它能比`return this.replace(/ [^ az]/ig,'').replace(/(?:^)做得更好.\W | [AZ] |\b\W |\S +)/克,`... (2认同)
  • @EdmundReed 您可以简单地将整个字符串转换为小写,然后再转换为驼峰大小写,方法是将 `.toLowerCase()` 方法链接到。例如。使用上面@tabrindle 的解决方案:`const toCamelCase = (str) => str.toLowerCase().replace(/(?:^\w|[AZ]|\b\w)/g, (ltr, idx) => idx === 0 ? ltr.toLowerCase() : ltr.toUpperCase()).replace(/\s+/g, '');` (2认同)

d4n*_*yll 80

如果有人使用lodash,则有一个_.camelCase()功能.

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

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

_.camelCase('__FOO_BAR__');
// ? 'fooBar'
Run Code Online (Sandbox Code Playgroud)

  • 为什么要为此目的安装整个 lodash 软件包,并且 OP 特别需要一种使用 javascript 正则表达式的解决方案。 (4认同)
  • @PeterMoses 1)我的答案是“_如果_有人使用lodash”,而不是“你应该安装Lodash来做到这一点”2)虽然问题正文指的是JavaScript RegEx,但很多人来到这里是因为标题是“将任何字符串转换为骆驼” case" 3) 您不需要导入“整个”lodash 库;您可以只导入您需要的方法,或者使用[**每个方法包**](https://lodash.com/per-method-packages),例如[`lodash.camelcase`](https://www. npmjs.com/package/lodash.camelcase) 代替(此后已被弃用) 4) 您可以通过实施 tree shake 来减轻大包的影响 (4认同)
  • 这个答案应该肯定会更进一步.Lodash提供了一套完整的设置,可以在不同情况下转换字符串. (2认同)

Sco*_*ach 47

我刚结束这样做:

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

我试图避免将多个替换语句链接在一起.我的功能中有1美元,2美元,3美元的东西.但是这种类型的分组很难理解,你提到的跨浏览器问题也是我从未想过的.

  • 如果您要使用String.prototype,为什么不使用'this'而不是发送'str'参数? (45认同)
  • 为了更好的浏览器兼容性,请使用此代替str(并从函数调用中删除参数) (6认同)
  • 这将返回与所需完全相反的结果。这将返回 STRING。 (3认同)
  • 你只需要使用 `this.valueOf()` 而不是传递 `str`。或者(如我的情况)`this.toLowerCase()`,因为我的输入字符串全部大写,没有将非驼峰部分正确小写。仅使用 `this` 返回字符串对象本身,它实际上是一个字符数组,因此会出现上面提到的 TypeError。 (2认同)

ism*_*iet 39

您可以使用此解决方案:

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('');
}
Run Code Online (Sandbox Code Playgroud)

  • +1表示*不*使用正则表达式,即使问题要求使用它们的解决方案.这是一个更清晰的解决方案,也是一个明显的性能胜利(因为处理复杂的正则表达式比仅仅迭代一堆字符串并将它们连接在一起要困难得多).请参阅https://jsperf.com/camel-casing-regexp-or-character-manipulation/1,其中我在这里采用了一些示例(以及我自己对性能的适度改进,尽管我在大多数情况下,为了清晰起见,可能更喜欢这个版本). (4认同)
  • 驼峰大小写是大写字母中每个单词的第一个字符,而toCamelCase函数就是这样做的。 (2认同)
  • 您正在考虑[PascalCase](https://en.wikipedia.org/wiki/PascalCase).[CamelCase](https://en.wikipedia.org/wiki/Camel_case)可以是大写或小写.在这种情况下,通常是小写以避免混淆. (2认同)

Fre*_*ric 26

在斯科特的具体案例中,我会选择以下内容:

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
Run Code Online (Sandbox Code Playgroud)

正则表达式将匹配第一个字符(如果它以大写字母开头)和任何字母字符后面的空格,即指定字符串中的2或3次.

通过加强正则表达式,/^([A-Z])|[\s-_](\w)/g它也将使用连字符和下划线类型名称.

'hyphen-name-format'.toCamelCase()     // -> hyphenNameFormat
'underscore_name_format'.toCamelCase() // -> underscoreNameFormat
Run Code Online (Sandbox Code Playgroud)

  • @AshwaniShukla 为了处理多个连字符和/或下划线,您必须在字符组中添加一个 _multiplier_ (`+`),即:`/^([AZ])|[\s-_]+(\w )/克` (3认同)

smi*_*ace 25

为了得到ç黄褐色的Ç ASE

ES5

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

ES6

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


为了获得ç黄褐色的小号 entence ç ASEP ASCAL Ç ASE

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

注意:
对于带有重音符号的语言。确实包含À-ÖØ-öø-ÿ以下正则表达式
.replace(/[^a-zA-ZÀ-ÖØ-öø-ÿ0-9]+(.)/g

  • ES6对我来说一切都变成了小写 (5认同)
  • 如果你传递驼峰字符串,它将不起作用。我们需要检查我们是否已经对字符串进行了camalized。 (3认同)
  • 最佳答案-简洁明了。 (2认同)
  • 当字符串以空格开头时,它无法正常工作:“一二”->“OneTwo”,应该是“oneTwo”。在我的回答中工作正常;) (2认同)

Eil*_*idh 21

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, '' );
}
Run Code Online (Sandbox Code Playgroud)

我试图找到一个camelCase字符串的JavaScript函数,并希望确保删除特殊字符(我无法理解上面的一些答案正在做什么).这是基于cc young的回答,添加了评论并删除了$ peci&l字符.


vit*_*y-t 18

可靠的高性能示例:

function camelize(text) {
    text = text.replace(/[-_\s.]+(.)?/g, (_, c) => c ? c.toUpperCase() : '');
    return text.substr(0, 1).toLowerCase() + text.substr(1);
}
Run Code Online (Sandbox Code Playgroud)

大小写变化字符:

  • 连字符 -
  • 下划线 _
  • 时期 .
  • 空间

  • 对于以大写字符串开头的人,首先使用:text = text.toLowerCase(); (2认同)

aza*_*oth 9

如果不需要正则表达式,你可能想看看下面的代码我做了一个很久以前的星星:

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 );
}
Run Code Online (Sandbox Code Playgroud)

我没有进行任何性能测试,regexp版本可能会或可能不会更快.


Pas*_*ery 9

这个函数绕过了cammelcase这样的测试

  • Foo Bar
  • --foo-bar--
  • __FOO_BAR__-
  • foo123Bar
  • foo_Bar

function toCamelCase(str)
{
  var arr= str.match(/[a-z]+|\d+/gi);
  return arr.map((m,i)=>{
    let low = m.toLowerCase();
    if (i!=0){
      low = low.split('').map((s,k)=>k==0?s.toUpperCase():s).join``
    }
    return low;
  }).join``;
}
console.log(toCamelCase('Foo      Bar'));
console.log(toCamelCase('--foo-bar--'));
console.log(toCamelCase('__FOO_BAR__-'));
console.log(toCamelCase('foo123Bar'));
console.log(toCamelCase('foo_Bar'));

console.log(toCamelCase('EquipmentClass name'));
console.log(toCamelCase('Equipment className'));
console.log(toCamelCase('equipment class name'));
console.log(toCamelCase('Equipment Class Name'));
Run Code Online (Sandbox Code Playgroud)


Bra*_*ell 8

为了有效地创建一个将字符串的大小写转换为驼峰式大小写的函数,该函数还需要先将每个字符串转换为小写字母,然后再将非第一个字符串的第一个字符的大小写转换为大写字母。

\n

我的示例字符串是:

\n
"text That I WaNt to make cAMEL case"\n
Run Code Online (Sandbox Code Playgroud)\n

针对此问题提供的许多其他解决方案都会返回以下内容:

\n
"textThatIWaNtToMakeCAMELCase"\n
Run Code Online (Sandbox Code Playgroud)\n

不过,我认为所需的输出是这样的,其中所有中间字符串大写字符首先转换为小写:

\n
"textThatIWantToMakeCamelCase"\n
Run Code Online (Sandbox Code Playgroud)\n

replace()这可以在不使用任何方法调用的情况下通过利用String.prototype.split()Array.prototype.map()Array.prototype.join()方法来完成:

\n

\xe2\x89\xa4 ES5 版本

\n
function makeCamelCase(str) {\n  return str\n    .split(\' \')\n    .map((e,i) => i\n      ? e.charAt(0).toUpperCase() + e.slice(1).toLowerCase()\n      : e.toLowerCase()\n    )\n    .join(\'\')\n}\n\nmakeCamelCase("text That I WaNt to make cAMEL case")\n// -> "textThatIWantToMakeCamelCase" \xe2\x9c\x85\n
Run Code Online (Sandbox Code Playgroud)\n

我将分解每一行的作用,然后以另外两种格式\xe2\x80\x94 ES6 和方法提供相同的解决方案String.prototype,尽管我建议不要像这样直接扩展内置 JavaScript 原型。

\n

解说员

\n
function makeCamelCase(str) {\n  return str\n    // split string into array of different words by splitting at spaces\n    .split(\' \')\n    // 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`.\n    .map((e,i) => i\n      // 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)\n      ? e.charAt(0).toUpperCase() + e.slice(1).toLowerCase()\n      // for the first word, we convert the entire word to lowercase\n      : e.toLowerCase()\n    )\n    // finally, we join the different strings back together into a single string without spaces, our camel-cased string\n    .join(\'\')\n}\n\nmakeCamelCase("text That I WaNt to make cAMEL case")\n// -> "textThatIWantToMakeCamelCase" \xe2\x9c\x85\n
Run Code Online (Sandbox Code Playgroud)\n

ES6+ 精简版(单行)

\n
const makeCamelCase = str => str.split(\' \').map((e,i) => i ? e.charAt(0).toUpperCase() + e.slice(1).toLowerCase() : e.toLowerCase()).join(\'\')\n\nmakeCamelCase("text That I WaNt to make cAMEL case")\n// -> "textThatIWantToMakeCamelCase" \xe2\x9c\x85\n
Run Code Online (Sandbox Code Playgroud)\n

String.prototype方法版本

\n
String.prototype.toCamelCase = function() {\n  return this\n    .split(\' \')\n    .map((e,i) => i\n      ? e.charAt(0).toUpperCase() + e.slice(1).toLowerCase()\n      : e.toLowerCase()\n    )\n    .join(\'\')\n}\n\n"text That I WaNt to make cAMEL case".toCamelCase()\n// -> "textThatIWantToMakeCamelCase" \xe2\x9c\x85\n
Run Code Online (Sandbox Code Playgroud)\n


ele*_*aar 7

我的ES6方法:

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"
Run Code Online (Sandbox Code Playgroud)


koh*_*oth 6

最佳答案很简洁,但它不能处理所有边缘情况。对于任何需要更强大的实用程序,没有任何外部依赖项的人:

function camelCase(str) {
    return (str.slice(0, 1).toLowerCase() + str.slice(1))
      .replace(/([-_ ]){1,}/g, ' ')
      .split(/[-_ ]/)
      .reduce((cur, acc) => {
        return cur + acc[0].toUpperCase() + acc.substring(1);
      });
}

function sepCase(str, sep = '-') {
    return str
      .replace(/[A-Z]/g, (letter, index) => {
        const lcLet = letter.toLowerCase();
        return index ? sep + lcLet : lcLet;
      })
      .replace(/([-_ ]){1,}/g, sep)
}

// All will return 'fooBarBaz'
console.log(camelCase('foo_bar_baz'))
console.log(camelCase('foo-bar-baz'))
console.log(camelCase('foo_bar--baz'))
console.log(camelCase('FooBar  Baz'))
console.log(camelCase('FooBarBaz'))
console.log(camelCase('fooBarBaz'))

// All will return 'foo-bar-baz'
console.log(sepCase('fooBarBaz'));
console.log(sepCase('FooBarBaz'));
console.log(sepCase('foo-bar-baz'));
console.log(sepCase('foo_bar_baz'));
console.log(sepCase('foo___ bar -baz'));
console.log(sepCase('foo-bar-baz'));

// All will return 'foo__bar__baz'
console.log(sepCase('fooBarBaz', '__'));
console.log(sepCase('foo-bar-baz', '__'));
Run Code Online (Sandbox Code Playgroud)

演示在这里:https : //codesandbox.io/embed/admiring-field-dnm4r?fontsize=14&hidenavigation=1&theme=dark


Ala*_*ois 5

lodash可以很好地做到这一点:

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

尽管它lodash可能是一个“大”库(〜4kB),但是它包含许多您通常使用摘要或自行构建的功能。


小智 5

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


Mar*_*ska 5

这是一个工作的班轮:

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

它根据RegExp中提供的字符列表分割小写字符串[.\-_\s](在[]!中添加更多),并返回一个word数组。然后,它将字符串数组简化为一个带有大写首字母的串联单词字符串。因为reduce没有初始值,所以它将以第二个单词开头的大写字母开头。

如果需要PascalCase,只需将一个初始的空字符串添加,'')到reduce方法中即可。


dx_*_*_dt 5

因为这个问题需要另一个答案......

我尝试了以前的几种解决方案,但它们都有一个或另一个缺陷。有些没有删除标点符号;有些没有处理数字的情况;有些没有连续处理多个标点符号。

他们都没有处理像a1 2b. 这种情况没有明确定义的约定,但其他一些stackoverflow 问题建议用下划线分隔数字。

我怀疑这是性能最高的答案(三个正则表达式通过字符串,而不是一两个),但它通过了我能想到的所有测试。不过,老实说,我真的无法想象您进行了如此多的驼峰式转换以至于性能很重要的情况。

(我将其添加为npm 包。它还包含一个可选的布尔参数,用于返回 Pascal Case 而不是 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();
        });
}
Run Code Online (Sandbox Code Playgroud)

测试用例(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`);
});
Run Code Online (Sandbox Code Playgroud)