亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將任何字符串轉換為駝峰式大小寫

將任何字符串轉換為駝峰式大小寫

Helenr 2019-11-11 14:08:21
如何使用javascript正則表達式將字符串轉換為駝峰式?EquipmentClass name或 Equipment className或equipment class name或Equipment Class Name應該全部變成:equipmentClassName。
查看完整描述

3 回答

?
絕地無雙

TA貢獻1946條經驗 獲得超4個贊

查看您的代碼,只需兩個replace調用即可實現:


function camelize(str) {

  return str.replace(/(?:^\w|[A-Z]|\b\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"

編輯:或只需單擊一次replace,即可在中捕獲空白RegExp。


function camelize(str) {

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

  });

}


查看完整回答
反對 回復 2019-11-11
?
呼啦一陣風

TA貢獻1802條經驗 獲得超6個贊

如果有人在使用lodash,則有一個_.camelCase()功能。


_.camelCase('Foo Bar');

// → 'fooBar'


_.camelCase('--foo-bar--');

// → 'fooBar'


_.camelCase('__FOO_BAR__');

// → 'fooBar'


查看完整回答
反對 回復 2019-11-11
?
呼如林

TA貢獻1798條經驗 獲得超3個贊

我剛結束這樣做:


String.prototype.toCamelCase = function(str) {

    return str

        .replace(/\s(.)/g, function($1) { return $1.toUpperCase(); })

        .replace(/\s/g, '')

        .replace(/^(.)/, function($1) { return $1.toLowerCase(); });

}

我試圖避免將多個replace語句鏈接在一起。在我的函數中有$ 1,$ 2,$ 3的東西。但是這種類型的分組很難理解,而您對跨瀏覽器問題的提及也是我從未想過的。


查看完整回答
反對 回復 2019-11-11
  • 3 回答
  • 0 關注
  • 1307 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號