如何使用javascript正则表达式将字符串转换为驼峰大小写?
设备类名称或 设备类名或设备类名或设备类名
应该全部变成:equipmentClassName。
如何使用javascript正则表达式将字符串转换为驼峰大小写?
设备类名称或 设备类名或设备类名或设备类名
应该全部变成:equipmentClassName。
当前回答
我最后是这样做的:
String.prototype.toCamelCase = function(str) {
return str
.replace(/\s(.)/g, function($1) { return $1.toUpperCase(); })
.replace(/\s/g, '')
.replace(/^(.)/, function($1) { return $1.toLowerCase(); });
}
我试图避免将多个替换语句链接在一起。函数中有1 2 3美元。但是这种类型的分组很难理解,你提到的跨浏览器问题也是我从未想过的。
其他回答
如果不需要regexp,你可能想看看我很久以前为Twinkle做的以下代码:
String.prototype.toUpperCaseFirstChar = function() {
return this.substr( 0, 1 ).toUpperCase() + this.substr( 1 );
}
String.prototype.toLowerCaseFirstChar = function() {
return this.substr( 0, 1 ).toLowerCase() + this.substr( 1 );
}
String.prototype.toUpperCaseEachWord = function( delim ) {
delim = delim ? delim : ' ';
return this.split( delim ).map( function(v) { return v.toUpperCaseFirstChar() } ).join( delim );
}
String.prototype.toLowerCaseEachWord = function( delim ) {
delim = delim ? delim : ' ';
return this.split( delim ).map( function(v) { return v.toLowerCaseFirstChar() } ).join( delim );
}
我没有做任何性能测试,regexp版本可能更快,也可能不会更快。
可靠的高性能示例:
function camelize(text) {
const a = text.toLowerCase()
.replace(/[-_\s.]+(.)?/g, (_, c) => c ? c.toUpperCase() : '');
return a.substring(0, 1).toLowerCase() + a.substring(1);
}
情况下,修改字符:
连字符- 下划线_ 时期。 空间
大多数答案不处理unicode字符,例如重音字符。
如果你想处理unicode和重音,在任何现代浏览器中都可以使用以下方法:
camelCase = s => s
.replace( /(?<!\p{L})\p{L}|\s+/gu,
m => +m === 0 ? "" : m.toUpperCase() )
.replace( /^./,
m => m?.toLowerCase() );
以下是一些解释:
因为问题要求第一个字符是小写的,所以必须调用第二个replace。 第一个replace调用标识任何跟在任何非字母后面的unicode字母(相当于\b\w,但适用于非ASCII字母)。为此,u标志(unicode)是必要的。
注意,这将保持大写字母不变。如果您的输入文本包含首字母缩略词,这很有用。
e.g.
console.log(camelCase("Shakespeare in FR is être ou ne pas être");
// => 'ShakespeareInFRIsÊtreOuNePasÊtre'
如果您想要纯驼峰大小写,其中首字母缩写变成小写,您可以先将输入文本小写。
Coderbyte Camel案例解决方案
问题:
让函数CamelCase(str)接受传入的str参数,并以适当的驼峰格式返回,其中每个单词的第一个字母都大写(不包括第一个字母)。字符串将只包含字母和分隔符标点符号的某种组合。
例如:如果str是"BOB loves-coding",那么你的程序应该返回字符串bobLovesCoding。
解决方案:
函数CamelCase(str) { 返回str .toLowerCase () .replace (/ (^ \ w) + () / g (ltr) = > ltr.toUpperCase ()) .replace (/ [^ a-zA-Z] / g,”); } //保留此函数调用 console.log(CamelCase(“猫和*狗-真棒”)); console.log(CamelCase("a b c d-e-f%g"));
去找骆驼凯斯
ES5
var camalize = function camalize(str) {
return str.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, function(match, chr)
{
return chr.toUpperCase();
});
}
ES6
var camalize = function camalize(str) {
return str.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, (m, chr) => chr.toUpperCase());
}
var camelSentence = function camelSentence(str) {
return (" " + str).toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, function(match, chr)
{
return chr.toUpperCase();
});
}
注意: 对于那些有口音的语言。是否包括如下的正则表达式À-ÖØ-öø- ux .replace (/ [^ a-zA-ZA-OØ- oø-y0-9) + () / g,这只是一种语言。对于另一种语言,你必须搜索和发现