Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How can I convert a string into camel case using javascript regex?(如何使用javascript正则表达式将字符串转换为驼峰式?)

EquipmentClass name or Equipment className or equipment class name or Equipment Class Name(EquipmentClass nameEquipment classNameequipment class nameEquipment Class Name)

should all become: equipmentClassName .(应该全部变为: equipmentClassName 。)

  ask by Scott Klarenbach translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
689 views
Welcome To Ask or Share your Answers For Others

1 Answer

Looking at your code, you can achieve it with only two replace calls:(查看您的代码,只需两个replace调用即可实现:)

function camelize(str) {
  return str.replace(/(?:^w|[A-Z]|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"

Edit: Or in with a single replace call, capturing the white spaces also in the RegExp .(编辑:或通过单个replace调用,也可以在RegExp捕获空白。)

function camelize(str) {
  return str.replace(/(?:^w|[A-Z]|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();
  });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...