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();
});
}
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一个字符串,并希望确保特殊字符将被删除(我有困难理解上面的一些答案正在做什么)。这是基于c c young的回答,增加了注释,并删除了$peci&l字符。
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('');
}
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
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" ✅
function camelize(dashString) {
let el = document.createElement('div')
el.setAttribute('data-'+dashString,'')
return Object.keys(el.dataset)[0]
}
camelize('x-element') // 'xElement'
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("a b c d-e-f%g"));
// 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"));