如何使用javascript正则表达式将字符串转换为驼峰大小写?
设备类名称或 设备类名或设备类名或设备类名
应该全部变成:equipmentClassName。
如何使用javascript正则表达式将字符串转换为驼峰大小写?
设备类名称或 设备类名或设备类名或设备类名
应该全部变成:equipmentClassName。
当前回答
遵循@Scott的可读性方法,做了一点微调
// convert any string to camelCase
var toCamelCase = function(str) {
return str.toLowerCase()
.replace( /['"]/g, '' )
.replace( /\W+/g, ' ' )
.replace( / (.)/g, function($1) { return $1.toUpperCase(); })
.replace( / /g, '' );
}
其他回答
我想出了这个内衬,它也适用于烤肉盒到骆驼盒:
string.replace(/^(.)|[\s-](.)/g,
(match) =>
match[1] !== undefined
? match[1].toUpperCase()
: match[0].toUpperCase()
)
Lodash可以很好地做到这一点:
var _ = require('lodash');
var result = _.camelCase('toto-ce héros')
// result now contains "totoCeHeros"
虽然lodash可能是一个“大”库(~4kB),但它包含了许多通常使用代码片段或自己构建的函数。
大多数答案不处理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'
如果您想要纯驼峰大小写,其中首字母缩写变成小写,您可以先将输入文本小写。
我最后是这样做的:
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美元。但是这种类型的分组很难理解,你提到的跨浏览器问题也是我从未想过的。
这就是我的解决方案:
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))