JS正则应用之代码化APP名

目的是写一个 JavaScript 函数,主要利用正则表达式,实现英文 APP 名的代码化。

何谓代码化?
即转化符合^[A-Za-z][A-Za-z\d'\+\-_ ]*$,举例以明之:

| APP英文名 | 代码化 | 注 |
| :--- | :--- | |
| Alipay | alipay | |
| MX Player | mx_player | |
| CoolApk | cool_apk | |
| BlueDict Pro | blue_dict_pro | |
| Camera360 | camera_360 | |
| ViPER4Android FX | vi_per_4_android_fx | |
| Today's Headline | todays_headline | |
| Moon+ Reader | moon_plus_reader | |
| X-plore | x_plore | |
| Minecraft - Pocket Edition | minecraft_pocket_edition | |
| JD.COM | jd_com | |
| QQMusic | qqmusic | 这种情况需要人工处理为qq_music,类似还有 QQi |
| 58Life | | 不能以非字母开头 |

function codeAppName(name) {
  if (!name) {
    return "";
  }
  name = name.trim();
  if (name.length == 0) {
    return "";
  }
  if (/^[A-Za-z][A-Za-z\d'\+\-\. _]*$/.test(name)) {
    var res;
    while ((res = /([a-z][A-Z])|([A-Za-z]\d)|(\d[A-Za-z])/.exec(name)) != null) {
      name = name.replace(res[0], res[0].charAt(0) + "_" + res[0].charAt(1));
    }
    return name.toLowerCase()
      .replace(/'/g, "")
      .replace(/\+/g, "_plus")
      .replace(/-|\.| /g, "_")
      .replace(/_{2,}/g, '_');
  }
  return "";
}

挑选具有代表性的英文 APP 名进行测试:



 
  
  Test
 
 



 

测试全部通过:

true: Alipay >>> alipay
true: MX Player >>> mx_player
true: CoolApk >>> cool_apk
true: BlueDict Pro >>> blue_dict_pro
true: Camera360 >>> camera_360
true: ViPER4Android FX >>> vi_per_4_android_fx
true: Today's Headline >>> todays_headline
true: Moon+ Reader >>> moon_plus_reader
true: X-plore >>> x_plore
true: Minecraft - Pocket Edition >>> minecraft_pocket_edition
true: JD.COM >>> jd_com
true: 58Life >>> 

你可能感兴趣的:(JS正则应用之代码化APP名)