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

设备类名称或 设备类名或设备类名或设备类名

应该全部变成:equipmentClassName。


当前回答

以下所有14个排列产生相同的“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()); };

其他回答

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

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

这个方法似乎比这里的大多数答案都要好,虽然有点粗糙,没有替换,没有正则表达式,只是建立一个新的字符串,那就是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;
}

基本的方法是用匹配大写或空格的正则表达式分割字符串。然后再把碎片粘回去。技巧将处理各种方式的正则表达式分割是破坏/奇怪的浏览器。有人编写了一个库来解决这些问题;我去找找。

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

简单容易理解这段代码,希望这对你有帮助,我用下面的逻辑解决了我的问题

// This example is for React Js User

const ConverToCamelCaseString = (StringValues)=> 
{
    let WordsArray = StringValues.split(" ");
    let CamelCaseValue = '';
    for (let index = 0; index < WordsArray.length; index++) 
    {
        let singleWord = WordsArray[index];
            singleWord.charAt(0).toUpperCase();
            singleWord =singleWord.charAt(0).toUpperCase() + singleWord.slice(1);

        CamelCaseValue +=" "+singleWord;
        
    }
    CamelCaseValue = CamelCaseValue.trim();
    return CamelCaseValue;
}

下面的例子是针对核心javaScript用户的

function ConverToCamelCaseString (StringValues) 
    {
        let WordsArray = StringValues.split(" ");
        let CamelCaseValue = '';
        for (let index = 0; index < WordsArray.length; index++) 
        {
            let singleWord = WordsArray[index];
                singleWord.charAt(0).toUpperCase();
                singleWord =singleWord.charAt(0).toUpperCase() + singleWord.slice(1);

            CamelCaseValue +=" "+singleWord;
            
        }
        CamelCaseValue = CamelCaseValue.trim();
        return CamelCaseValue;
    }

console.log(ConverToCamelCaseString("this is my lower case string")); 

我希望上面的例子能解决你的问题。

我认为这应该可行。

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