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

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

应该全部变成:equipmentClassName。


当前回答

这建立在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

其他回答

这就是我的解决方案:

const toCamelWord = (word, idx) => Idx === 0 ? word.toLowerCase (): word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); const toCamelCase = text => 文本 .split (/ [_ - \] + /) . map (toCamelWord) . join (" "); console.log (toCamelCase(用户ID))

我认为这应该可行。

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

在斯科特的具体情况下,我会这样说:

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次。

通过将正则表达式添加到/^([A-Z])|[\s-_](\w)/g,还可以简化连字符和下划线类型的名称。

'hyphen-name-format'.toCamelCase()     // -> hyphenNameFormat
'underscore_name_format'.toCamelCase() // -> underscoreNameFormat
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函数驼峰大小写字符串,并希望确保特殊字符将被删除(我有困难理解上面的一些答案正在做什么)。这是基于c c young的回答,添加了注释,并删除了$peci&l字符。

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

// 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")); 

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