如何使用javascript正则表达式将字符串转换为驼峰大小写?
设备类名称或 设备类名或设备类名或设备类名
应该全部变成:equipmentClassName。
如何使用javascript正则表达式将字符串转换为驼峰大小写?
设备类名称或 设备类名或设备类名或设备类名
应该全部变成:equipmentClassName。
当前回答
这为我解决了这个问题,处理特殊字符和介词
export function camelize(str) {
if (!str) {
return str;
}
const preposicoes = ['da', 'de', 'di', 'do', 'du'];
return str.toLowerCase().split(' ').map(c => {
if (preposicoes.includes(c)) {
return c;
}
return `${c.substring(0, 1).toUpperCase()}${c.substring(1, c.length)}`;
}).join(' ');
}
其他回答
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字符。
编辑:现在工作在IE8没有变化。
编辑:我对camelCase到底是什么持少数意见(主角小写vs大写)。一般来说,社区认为开头小写字母是camel大小写,开头大写字母是pascal大小写。我创建了两个只使用正则表达式模式的函数。所以我们使用统一的词汇我已经改变了我的立场以配合大多数人。
我相信在这两种情况下你只需要一个正则表达式:
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"
or
var pascal = " this IS pascal case "
pascal = $.trim(pascal)
.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 "ThisIsPascalCase"
在函数中:你会注意到,在这些函数中,replace是将任何非a-z与空格与空字符串交换。这是为大写创建单词边界。"hello-MY#world" -> "HelloMyWorld"
// remove \u00C0-\u00ff] if you do not want the extended letters like é
function toCamelCase(str) {
var retVal = '';
retVal = $.trim(str)
.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, '');
return retVal
}
function toPascalCase(str) {
var retVal = '';
retVal = $.trim(str)
.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, '');
return retVal
}
注:
为了可读性,我保留了A-Za-z vs为模式(/[^A-Z]/ig)添加大小写不敏感标志(I)。 这可以在IE8中工作(srsly,谁还在使用IE8呢。)使用我在IE11、IE10、IE9、IE8、IE7和IE5中测试过的(F12)开发工具。适用于所有文档模式。 这将正确地对以空格或不以空格开头的字符串的第一个字母进行大小写区分。
享受
为了有效地创建一个将字符串的大小写转换为驼峰式大小写的函数,该函数还需要首先将每个字符串转换为小写,然后再将非第一个字符串的第一个字符转换为大写字母。
我的示例字符串是:
"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格式和字符串格式。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.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" ✅
简单容易理解这段代码,希望这对你有帮助,我用下面的逻辑解决了我的问题
// 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 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"
编辑:或者使用一个替换调用,捕获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();
});
}