繁体   English   中英

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

[英]Converting any string into camel case

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

EquipmentClass name类名称或设备类名称或设备Equipment className equipment class nameEquipment Class Name

都应该变成: equipmentClassName

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

编辑:或者在单个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();
  });
}

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

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

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

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

获取骆驼Case

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

> 获取 ***C**amel**S**entence**C**ase* 或 ***P**ascal**C**ase*
 var camelSentence = function camelSentence(str) { return (" " + str).toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, function(match, chr) { return chr.toUpperCase(); }); }

笔记 :
对于那些有口音的语言。 请在正则表达式中包含À-ÖØ-öø-ÿ ,如下所示
.replace(/[^a-zA-ZÀ-ÖØ-öø-ÿ0-9]+(.)/g这仅适用于一种语言。对于另一种语言,您必须搜索并找到

我刚结束这样做:

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

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

您可以使用此解决方案:

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

在斯科特的具体情况下,我会选择类似的东西:

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

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

通过将正则表达式添加到/^([AZ])|[\s-_](\w)/g它还将使连字符和下划线类型名称驼峰化。

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

可靠的高性能示例:

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

大小写转换字符:

  • 连字符-
  • 下划线_
  • 期间.
  • 空间
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, '' );
}

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

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

我还没有进行任何性能测试,正则表达式版本可能会也可能不会更快。

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

这是一个做这项工作的班轮:

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

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

如果你想要 PascalCase,只需在 reduce 方法中添加一个初始的空字符串,'')

这个函数通过cammelcase这样的测试

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

 function toCamelCase(str) { var arr= str.match(/[az]+|\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'));

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

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

尽管lodash可能是一个“大”库 (~4kB),但它包含许多您通常会使用代码片段或自己构建的功能。

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

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

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

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

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

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

他们都没有处理像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();
        });
}

测试用例(开玩笑)

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

遵循@Scott 的可读方法,进行一些微调

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

很少修改斯科特的答案:

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

现在它也替换了“-”和“_”。

以下所有 14 种排列产生相同的“设备类名称”结果。

 String.prototype.toCamelCase = function() { return this.replace(/[^az ]/ig, '') // Replace everything but letters and spaces. .replace(/(?:^\w|[AZ]|\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()); };

您可以使用此解决方案:

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

这是我的建议:

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

或者

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

测试用例:

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

有我的解决方案:

 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'))

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

我的示例字符串是:

"text That I WaNt to make cAMEL case"

为这个问题提供的许多其他解决方案都返回了这个:

"textThatIWaNtToMakeCAMELCase"

我认为应该是预期的,期望的输出是这样的,其中所有中间字符串大写字符首先转换为小写:

"textThatIWanrtToMakeCamelCase"

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

≤ 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")
// -> "textThatIWanrtToMakeCamelCase" ✅

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

解说员

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")
// -> "textThatIWanrtToMakeCamelCase" ✅

精简 ES6+(单行)版本

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")
// -> "textThatIWanrtToMakeCamelCase" ✅

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()
// -> "textThatIWanrtToMakeCamelCase" ✅

这种方法似乎胜过这里的大多数答案,虽然它有点hacky,没有替换,没有正则表达式,只是建立一个新的字符串,即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;
}

这建立在 CMS 的答案之上,方法是删除任何非字母字符,包括下划线, \w不会删除这些字符。

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

在不使用正则表达式的情况下将大写驼峰式(“TestString”)转换为小写驼峰式(“testString”)(让我们面对现实吧,正则表达式是邪恶的):

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

我最终制定了一个更具侵略性的解决方案:

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

上面的这个将删除所有非字母数字字符和单词的小写部分,否则它们会保持大写,例如

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

我知道这是一个旧答案,但这可以处理空格和 _ (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"
const toCamelCase = str =>
  str
    .replace(/[^a-zA-Z0-9]+(.)/g, (m, chr) => chr.toUpperCase())
    .replace(/^\w/, c => c.toLowerCase());

大多数答案不处理 unicode 字符,例如重音字符。

如果您想处理 unicode 和重音符号,以下适用于任何现代浏览器:

camelCase = s => s
   .replace( /(?<!\p{L})\p{L}|\s+/gu,
              m => +m === 0 ? "" : m.toUpperCase() )
   .replace( /^./, 
             m => m?.toLowerCase() );

几个解释:

  1. 因为问题要求第一个字符是小写的,所以第二个替换调用是必要的。
  2. 第一个 replace 调用标识任何非字母之后的任何 unicode 字母(相当于 \b\w 但适用于非 ASCII 字母)。 u 标志(unicode)是这个工作所必需的。

请注意,这将保持大写字母不变。 如果您的输入文本包含首字母缩略词,这很有用。

例如

console.log(camelCase("Shakespeare in FR is être ou ne pas être");
// => 'ShakespeareInFRIsÊtreOuNePasÊtre'

如果您想要将首字母缩略词变为小写的纯 camelCase,您可以先将输入文本小写。

基本方法是使用匹配大写或空格的正则表达式拆分字符串。 然后你会把这些碎片粘在一起。 技巧将处理正则表达式拆分在浏览器中被破坏/奇怪的各种方式。 有人写了一个图书馆或其他东西来解决这些问题; 我会去找的。

这是链接:http: //blog.stevenlevithan.com/archives/cross-browser-split

["


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"

不要使用 String.prototype.toCamelCase() 因为 String.prototypes 是只读的,大多数 js 编译器都会给你这个警告。

像我一样,那些知道字符串总是只包含一个空格的人可以使用一种更简单的方法:

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

祝你有美好的一天。 :)

我想出了一个衬里,它也适用于 CamelCase 的 kebab-case:

string.replace(/^(.)|[\s-](.)/g,
                (match) =>
                    match[1] !== undefined
                        ? match[1].toUpperCase()
                        : match[0].toUpperCase()
            )

有一个包可以做到这一点

import (
    "fmt"
    "github.com/buxizhizhoum/inflection"
)

func example () {
    // to convert a string to underscore
    res := inflection.Underscore("aA")
    // will return a_a
    fmt.Println(res)
    // to convert a string to camelize
    // will return AA
    fmt.Println(inflection.Camelize("a_a", true))
}

一种有趣的方法是通过数据集属性。

 function camelize(dashString) { let el = document.createElement('div') el.setAttribute('data-'+dashString,'') return Object.keys(el.dataset)[0] } camelize('x-element') // 'xElement'

Coderbyte 骆驼案例解决方案

问题:

让 function CamelCase(str) 获取传递的 str 参数,并以正确的驼峰格式返回它,其中每个单词的第一个字母大写(不包括第一个字母)。 该字符串将仅包含字母和分隔每个单词的分隔符标点字符的某种组合。

例如:如果 str 是“BOBloves-coding”,那么你的程序应该返回字符串 bobLovesCoding。

解决方案:

 function CamelCase(str) { return str.toLowerCase().replace(/[^\w]+(.)/g, (ltr) => ltr.toUpperCase()).replace(/[^a-zA-Z]/g, ''); } // keep this function call here console.log(CamelCase("cats AND*Dogs-are Awesome")); console.log(CamelCase("ab c def%g"));

我认为这应该工作..

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

一个超级简单的方法,使用 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>

您还可以使用 StringUtils.FORMAT_CAMEL_CASE 和 StringUtils.FORMAT_UPPER_CAMEL_CASE 生成首字母大小写变化。

更多信息在这里:

将字符串转换为 CamelCase、UpperCamelCase 或 lowerCamelCase

这会将任何带有空格的大小写字符串转换为 thisWordsInCamelCase

String.prototype.toCamelCase = function () {
  return this.toString() && this.split(' ').map((word, index) => {
    return (index === 0 ? word[0].toLowerCase() : word[0].toUpperCase()) + word.slice(1).toLowerCase()
  }).join('');
}

快捷方式

function toCamelCase(str) {
    return str[0].toUpperCase() + str.substr(1).toLowerCase();
}

 function camelCase(str) { return str.split(' ').map((x) => x.charAt(0).toUpperCase() + x.slice(1)).join(''); } console.log(camelCase('camel case word'));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM