如何使用javascript正则表达式将字符串转换为驼峰大小写?
设备类名称或 设备类名或设备类名或设备类名
应该全部变成:equipmentClassName。
如何使用javascript正则表达式将字符串转换为驼峰大小写?
设备类名称或 设备类名或设备类名或设备类名
应该全部变成:equipmentClassName。
当前回答
这建立在CMS的答案上,通过删除包括下划线在内的任何非字母字符,\w不会删除这些字符。
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
其他回答
一个超级简单的方法,使用turboCommons库:
npm install turbocommons-es5
<script src="turbocommons-es5/turbocommons-es5.js"></script>
<script>
var StringUtils = org_turbocommons.StringUtils;
console.log(StringUtils.formatCase('EquipmentClass', StringUtils.FORMAT_LOWER_CAMEL_CASE));
console.log(StringUtils.formatCase('Equipment className', StringUtils.FORMAT_LOWER_CAMEL_CASE));
console.log(StringUtils.formatCase('equipment class name', StringUtils.FORMAT_LOWER_CAMEL_CASE));
console.log(StringUtils.formatCase('Equipment Class Name', StringUtils.FORMAT_LOWER_CAMEL_CASE));
</script>
你也可以使用StringUtils。FORMAT_CAMEL_CASE和StringUtils。FORMAT_UPPER_CAMEL_CASE生成首字母大小写的变化。
更多信息:
将字符串转换为驼峰,UpperCamelCase或lowerCamelCase
您可以使用以下解决方案:
String.prototype.toCamelCase = function(){ return this.replace(/\s(\w)/ig, function(all, letter){return letter. touppercase ();}) .replace (/ (^ \ w)、功能(1美元){返回1.美元tolowercase ()}); }; console.log(“设备名称”.toCamelCase ());
不要使用String.prototype. tocamelcase(),因为String。原型是只读的,大多数js编译器会给你这个警告。
像我一样,那些知道字符串总是只包含一个空格的人可以使用一种更简单的方法:
let name = 'test string';
let pieces = name.split(' ');
pieces = pieces.map((word, index) => word.charAt(0)[index===0 ? 'toLowerCase' :'toUpperCase']() + word.toLowerCase().slice(1));
return pieces.join('');
祝你有愉快的一天。:)
大多数答案不处理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'
如果您想要纯驼峰大小写,其中首字母缩写变成小写,您可以先将输入文本小写。
基本的方法是用匹配大写或空格的正则表达式分割字符串。然后再把碎片粘回去。技巧将处理各种方式的正则表达式分割是破坏/奇怪的浏览器。有人编写了一个库来解决这些问题;我去找找。
这是链接:http://blog.stevenlevithan.com/archives/cross-browser-split