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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2970525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:44:46  来源:igfitidea点击:

Converting any string into camel case

javascriptregexcamelcasing

提问by Scott Klarenbach

How can I convert a string into camel case using javascript regex?

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

EquipmentClass nameor Equipment classNameor equipment class nameor Equipment Class Name

EquipmentClass nameEquipment classNameequipment class nameEquipment Class Name

should all become: equipmentClassName.

都应该变成:equipmentClassName

采纳答案by Scott Klarenbach

I just ended up doing this:

我刚刚结束了这样做:

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

I was trying to avoid chaining together multiple replace statements. Something where I'd have $1, $2, $3 in my function. But that type of grouping is hard to understand, and your mention about cross browser problems is something I never thought about as well.

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

回答by CMS

Looking at your code, you can achieve it with only two replacecalls:

查看您的代码,您只需两次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"

Edit:Or in with a single replacecall, capturing the white spaces also in the RegExp.

编辑:或者通过一次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();
  });
}

回答by d4nyll

If anyone is using lodash, there is a _.camelCase()function.

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

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

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

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

回答by ismnoiet

You can use this solution :

您可以使用此解决方案:

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

回答by smilyface

To get camelCase

为了得到ç黄褐色的ÇASE

ES5

ES5

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

ES6

ES6

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



To get CamelSentenceCaseor PascalCase

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

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

Note :
For those language with accents. Do include à-??-??-?with the regex as following
.replace(/[^a-zA-Zà-??-??-?0-9]+(.)/g

注意:
对于那些带有口音的语言。包括à-??-??-?与正则表达式如下
.replace(/[^a-zA-Zà-??-??-?0-9]+(.)/g

回答by Fredric

In Scott's specific case I'd go with something like:

在 Scott 的具体案例中,我会采用以下方法:

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

The regex will match the first character if it starts with a capital letter, and any alphabetic character following a space, i.e. 2 or 3 times in the specified strings.

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

By spicing up the regex to /^([A-Z])|[\s-_](\w)/git will also camelize hyphen and underscore type names.

通过添加正则表达式,/^([A-Z])|[\s-_](\w)/g它也会使连字符和下划线类型名称骆驼化。

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

回答by Eilidh

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() { return .toUpperCase(); })
    // Removes spaces 
    .replace( / /g, '' );
}

I was trying to find a JavaScript function to camelCasea string, and wanted to make sure special characters would be removed (and I had trouble understanding what some of the answers above were doing). This is based on c c young's answer, with added comments and the removal of $peci&l characters.

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

回答by azatoth

If regexp isn't required, you might want to look at following code I made a long time ago for Twinkle:

如果不需要正则表达式,您可能需要查看我很久以前为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 );
}

I haven't made any performance tests, and regexp versions might or might not be faster.

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

回答by eledgaar

My ES6approach:

我的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"

回答by vitaly-t

Reliable working example that I've been using for years:

我多年来一直使用的可靠工作示例:

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

Case-changing characters include:

大小写变化的字符包括:

  • hyphen
  • underscore
  • period
  • space
  • 连字符
  • 下划线
  • 时期
  • 空间