JavaScript 如何将字符串转换为驼峰命名法
在本文中,给定一个字符串,任务是使用JavaScript将其转换为驼峰命名法。在此情况下,字符串的第一个字符将转换为小写,空格后的其他字符将转换为大写字符。
转换字符串为驼峰命名法的方法:
- 使用JavaScript的str.replace()方法与正则表达式
- 使用JavaScript的reduce()和split()方法
方法1:使用JavaScript的str.replace()方法
使用str.replace()方法来替换字符串的第一个字符为小写,并将空格后的其他字符设为大写。toUpperCase()和toLowerCase()方法用于将字符串字符转换为大写和小写。
示例1: 此示例使用RegExp、toLowerCase()和toUpperCase()方法将字符串转换为驼峰命名法。
// Input string with spaces
let str = 'Click the button to convert to camelCase';
// Function to convert into camel Case
function camelCase(str) {
// Using replace method with regEx
return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function (word, index) {
return index == 0 ? word.toLowerCase() : word.toUpperCase();
}).replace(/\s+/g, '');
}
// To display output
function gfg_Run() {
console.log(camelCase(str));
}
// Function call
gfg_Run()
输出
clickTheButtonToConvertToCamelCase
示例2: 这个示例使用replace()、toLowerCase()和toUpperCase()方法将一个字符串转换为驼峰命名法。
let str = 'Click the button to convert to camelCase';
function camelCase(str) {
return str
.replace(/\s(.)/g, function (a) {
return a.toUpperCase();
})
.replace(/\s/g, '')
.replace(/^(.)/, function (b) {
return b.toLowerCase();
});
}
function gfg_Run() {
console.log(camelCase(str));
}
gfg_Run()
输出
clickTheButtonToConvertToCamelCase
方法2:使用JavaScript的reduce()和split()方法
使用reduce()方法遍历字符串的字符,并将其转换为驼峰式大小写。使用toUpperCase()和toLowerCase()方法分别将字符串字符转换为大写和小写。
示例1: 这个示例使用reduce()、toLowerCase()和toUpperCase()方法将字符串转换为驼峰式大小写。
let str = 'Click the button to convert to camelCase';
function camelCase(str) {
// converting all characters to lowercase
let ans = str.toLowerCase();
// Returning string to camelcase
return ans.split(" ").reduce((s, c) => s
+ (c.charAt(0).toUpperCase() + c.slice(1)));
}
function gfg_Run() {
console.log(camelCase(str));
}
gfg_Run()
输出
clickTheButtonToConvertToCamelcase