zhangxinxu / quiz

小测答题收集区
536 stars 43 forks source link

JS基础测试42期 #58

Open zhangxinxu opened 4 years ago

zhangxinxu commented 4 years ago

本期关于字符打点处理,是下半学期最后一期。

题目图片访问

题目出现字符:title = '🎅🎄🎁❤️🚀圣诞快乐,系列有9了'

积分:2,2,4.

诚实守信,不要查看别人回答,如果不会,留空即可

大家提交回答的时候,注意缩进距离,起始位置从左边缘开始;另外,github自带代码高亮,所以请使用下面示意的格式(1积分)。

```js
// 你的JS代码写在这里
 ```

其它:

  1. 首位答题者可获得直播翻牌机会;
  2. 本次答疑直播为12月28日上午10:00,和上一期CSS小测一起,预计60分钟。会有年终小结;
JaimeCheng commented 4 years ago
// 1
function formatTitle (str) {
  return str.length <= 15 ? str : str.substr(0, 6) + '...' + str.substr(-6)
}
title = formatTitle(title)

// 2
//zxx: 后缀名不一定都是3个字符
function formatFilename (str) {
  return str.length <= 15 ? str : str.substr(0, 7) + '...' + str.substring(str.lastIndexOf('.') - 1)
}
filename = formatFilename(filename)

// 3 实在没头绪,只处理了同题1的,也不太对。
var reg = /\,|\:|\;|\——|\……|\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD]|[\u2660-\u2767]\u0020)/g
function formatSpecialStr (str) {
  if (!str.match(reg)) {
    return formatTitle(str)
  } else { ... }
}
guqianfeng commented 4 years ago
        {
            function prettyTitle(title, ruleLength = 15){
                if(title.length > ruleLength){
                    return title.replace(/^(.{6}).*(.{6})$/g, function(a, b, c){
                        return b + "..." + c;
                    })
                }
                return title;
            }

            function prettyFilename(filename, ruleLength = 15){
                if(filename.length > ruleLength ){
                    return filename.replace(/^(.*)(.\..*)$/g, function(a, b, c){
                        let tail = "..." + c;
                        let startLength = 15 - tail.length;
                        let start = b.substr(0, startLength);
                        return start + tail;
                    })
                }
                return filename;
            }

            //1
            let title = "abcd".repeat(4);
            console.log(prettyTitle(title));

            //2
            let filename = "weixin_20191221232646.jpg"
            console.log(prettyFilename(filename));

            //3 暂时没想到好的方案后续空了再补充
        }
les-lee commented 4 years ago
   var title = '啊啊啊了火辣升级过了阿拉斯加公司噶个阿萨德发个收工哦哦哦'
    // 1.
    function strFormat(str) {
      return str.length < 15 ? str : str.replace(/^(.{6})(?:.+)(.{6})$/, function (_, p1, p2, index, origin) {
        return p1 + '...' + p2
      })
    }
    console.log(strFormat(title))

    // 2.
    var filename = 'ojoisgd_6515641685.png'
    function filenameFormat(filename) {
      return filename.length < 15 ? filename : filename.replace(/^(.+)(\w\.[a-z0-9]+)$/, function (_, p1, p2, index, origin) {
        return p1.substr(0, 12 - p2.length) + '...' + p2
      })
    }
    console.log(filenameFormat(filename))
    // 3.
    // 留空
xingorg1 commented 4 years ago
// 第1题
function centerDot(str, total, num) {
  /* 
    str为要处理的字符,total为长度,num为要预留的字数
  */
  if (str.length > total) {
    str = str.substr(0, num) + '...' + str.substr(str.length - num)
  }
  return str;
}
// 第2题
function centerDotFileName(str, total, fillTxt) {
  /* 
    str为要处理的字符,total为最后生成文字总长度,为分隔的文案
  */
  var lastLetter = str.substr(str.indexOf('.') - 1)
  if (str.length > total) {
    str = str.substr(0, total - lastLetter.length - fillTxt.length) + fillTxt + lastLetter
  }
  return str;
}

//zxx: 执行centerDotFileName('weixin_2020299384.v.23.pptx', 15, '...');
// "w...4.v.23.pptx" 是不符合要求的哦
Despair-lj commented 4 years ago

第三题例子

// 1
function simpleHandleTitle(title) {
  if (title.length >= 15) {
    title = title.slice(0, 6) + '...' + title.slice(-6);
  }
  return title;
}

// 2
var filename = 'weixin_20191221232646.jpg';
if (filename.length > 15) {
  var idx = filename.lastIndexOf('.');
  var frontLen = 15 - (filename.length - idx + 1 + 3);
  filename = filename.slice(0, frontLen) + '...' + filename.slice(idx - 1);
}

// 3 因 emoji 的字符串长度不固定,选用工具库进行分组
// zxx: 补充:
// https://github.com/orling/grapheme-splitter
// A JavaScript library that breaks strings into their individual user-perceived characters.
var GraphemeSplitter = require('grapheme-splitter');
var splitter = new GraphemeSplitter();
var chineseSymbol = [',', ':', '——', '……'];
var emojiRex = /(\ud83c[\udf00-\udfff])|(\ud83d[\udc00-\ude4f\ude80-\udeff])|[\u2600-\u2B55]/g;

function handleStr(title) {
  var arr = splitter.splitGraphemes(title);
  // 处理破折号
  var firstDashIdx = arr.indexOf('—');
  if (
    firstDashIdx > -1 &&
    arr.length - 1 > firstDashIdx &&
    arr[firstDashIdx + 1] === '—'
  ) {
    arr[firstDashIdx] = '——';
    arr.splice(firstDashIdx + 1, 1);
  }
  // 处理破折号
  var firstEllIdx = arr.indexOf('…');
  if (
    firstEllIdx > -1 &&
    arr.length - 1 > firstEllIdx &&
    arr[firstEllIdx + 1] === '…'
  ) {
    arr[firstEllIdx] = '……';
    arr.splice(firstEllIdx + 1, 1);
  }
  if (arr.length < 15) return title;
  var length = arr.length;
  var half = Math.floor(length / 2);
  var start = length % 2 === 0 ? half - 1 : half;
  var end = half;
  var handleLeft = true;
  while (start + length - end - 1 > 12) {
    if (handleLeft) {
      start -= 1;
      // 当检测到 emoji 或者是 , 等符号是向左捕获字符
      if (emojiRex.test(arr[start - 1]) || chineseSymbol.indexOf(arr[start - 1]) > -1) {
        start -= 1;
        end -= 1;
      } else {
        handleLeft = false;
      }
    } else {
      end += 1;
       // 当检测到 emoji 或者是 , 等符号是向右捕获字符
      if (emojiRex.test(arr[end + 1]) || chineseSymbol.indexOf(arr[end + 1]) > -1) {
        start += 1;
        end += 1;
      } else {
        handleLeft = true;
      }
    }
  }

  return arr
    .slice(0, start)
    .concat('...', arr.slice(end + 1))
    .join('');
}
asyncguo commented 4 years ago
// 第一题
function titleAddEllipsis(str) {
  let strArr = [...str];

  return strArr.length > 15
    ? `${strArr.slice(0, 6).join("")}...${strArr.slice(-6).join("")}`
    : str;
}
// 第二题
function filenameAddEllipsis(str) {
  let strArr = [...str];
  if (strArr.length > 15) {
    let dotIndex = strArr.lastIndexOf(".");
    let rightStrArr = strArr.slice(dotIndex - 1);

    return `${strArr
      .slice(0, 12 - rightStrArr.length)
      .join("")}...${rightStrArr.join("")}`;
  } else {
    return str;
  }
}
// 第三题
function symbolAddEllipsis(str) {
  let strArr = [...str];

  if (strArr.length > 15) {
    let len = strArr.length;
    let half = parseInt(len / 2) - 1;

    let left = half;
    let right = half + 1;

    let pattern = /([\ud800-\udbff][\udc00-\udfff]|[\u2600-\u2B55])|([,;:—…])/g;

    while (left + len - right - 1 > 12 || left > 0) {
      if (pattern.test(strArr[left]) && left <= 6) {
        right = right + 1 - left;
        left = left - 2;
        break;
      }

      if (pattern.test(strArr[right]) && right >= len - 6) {
        right = right + 1;
        left = len - right + 4;
        break;
      }

      left -= 1;
      right += 1;
    }

    return left === 0
      ? titleAddEllipsis(str)
      : `${strArr.slice(0, left).join("")}...${strArr.slice(right).join("")}`;
  } else {
    return str;
  }
}

let _title1 = "🎅🎄🎁❤️🚀圣诞快乐,系列有9了";
let _title2 = "🎅🎄🎁❤️大家圣诞快乐,系列有9了";
let _title3 = "在这里祝大家圣诞快乐系列有9!";

console.log("===============================");
console.log(symbolAddEllipsis(_title1));
console.log("_title1:", "🎅🎄🎁...圣诞快乐,系列有9了");
console.log(symbolAddEllipsis(_title2));
console.log("_title2:", "🎅🎄🎁❤️大家圣诞...系列有9了");
console.log(symbolAddEllipsis(_title3));
console.log("_title3:", "在这里祝大家...乐系列有9!");
console.log("===============================");

// 另外一个思路是:只要当前字符个数大于15,便截取前8个+后8个,组成新的字符再进行过滤,不知道是否可以?
XboxYan commented 4 years ago
// 第一题
function elsMid(str, len) {
    var t = len || 15;
    if (str.length > t) {
        var after = parseInt(t / 2) - 1;
        return str.slice(0, t - after - 3) + '...' + str.slice(-after);
    }
    return str
}

console.log(elsMid('这是一段很长的文字,需要中间省略,因为首尾的信息都很重要'));

// 第二题
function elsFilename(str, len) {
    var t = len || 15;
    if (str.length > t) {
        var after = str.split('.').slice(-1)[0].length + 2; //最后一个点
        return str.slice(0, t - after - 3) + '...' + str.slice(-after);
    }
    return str
}

console.log(elsFilename('weixin_20191254656563.jpg'));
console.log(elsFilename('weixin_20191254611.bak.word'));

// 第三题
function elsEmoji(str, len) {
    var t = len || 15;
    var emojiArr = str.replace(/——|……|[^\ud83c|\ud83d]/g, function ($0) {
        if (/——|……/.test($0)) {
            return $0 + ',';
        }
        if (/[\u2000-\u2fff]/g.test($0)) {
            return $0
        }
        return $0 + ',';
    }).slice(0, -1).split(','); //转化成数组,不知道这样全不全

    if (emojiArr.length >= t) {
        var reg = /\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]|[\u2000-\u2fff]|——|……|,|:|;/g
        var mid = parseInt(emojiArr.length / 2);
        var before = emojiArr.slice(0, mid);
        var after = emojiArr.slice(mid);
        var index = 0;
        for (var i = 0; i < mid; i++) {
            if (reg.test(before[mid - i - 1])) {
                index = mid - i - 1;
                break;
            }
            if (reg.test(after[i])) {
                index = mid + i;
                break;
            }
        }

        var start = t - (emojiArr.length - index - 1) - 3;
        if (start <= 0 || index === emojiArr.length) {
            return elsMid(str);
        } else {
            return emojiArr.slice(0, start).join('') + '...' + emojiArr.slice(index + 1).join('');
        }
    }
    return str
}

console.log(elsEmoji('🎅🎄🎁❤️🚀🚀🚀圣诞快乐,系列有🚀了'))
console.log(elsEmoji('🎅🎄🎁❤️🚀❤️圣诞快乐,系列有🚀了'))
console.log(elsEmoji('🎅🎄🎁大家圣诞快乐——系列有🚀了'))
console.log(elsEmoji('🎅🎄🎁大家圣诞快乐❤️系列有🚀了'))
console.log(elsEmoji('🎅🎄🎁大家圣诞快乐……系列有🚀了'))
whrice commented 4 years ago
//1
function formatTitleOmit(title) {
  let len = title.length;
  return len > 15
      ? title.substr(0, 6) + "..." + title.substr(len - 6, 6)
       : title;
}
//2
function formatFileOmit(filename) {
    let len = filename.length;
    if (len > 15) {
        let index = filename.lastIndexOf(".");
        let suffix = len - index - 1;
        let start = 12 - (suffix + 2);
         return (
            filename.substr(0, start) +
            "..." +
            filename.substr(len - (suffix + 2), suffix + 2)
          );
     }
   return filename;
 }
//3
function formatSymbolOmit(str, key) {
        //key:表示设置关键字符
        let len = str.length;
        let omit = len-12;
        if (omit > 0) {
          let index = str.indexOf(key);
         return str.substring(0,index-3)+'...'+str.substring(index, len);
        }
        //不知道能不能从关键字符开始推,接下来就没有思路了
      }
  console.log(formatSymbolOmit('🎅🎄🎁❤️🚀圣诞快乐,系列有9了','圣诞'))
xxf1996 commented 4 years ago
// 第一题
function clipTitle (title) {
  let len = title.length
  return len > 15 ? `${title.substring(0, 6)}...${title.substring(len - 6)}` : title
}

// 第一题方法2:使用正则替换
function clipTitle2 (title) {
  return title.length > 15 ? title.replace(/^(.{6}).+(.{6})$/, '$1...$2') : title
}

// 第二题
function clipFilename (filename) {
  let len = filename.length
  let res = filename

  if (len > 15) {
    let end = filename.match(/.+(.{1}\..+)$/)[1] // 后缀加前一位字符
    res = `${filename.substring(0, 12 - end.length)}...${end}`
  }

  return res
}

// 第三题:看示例好像是把emoji表情看成一个字符?
// 测试了下,
// console.log(clipTitle3 ('🎅🎄🎁❤️🚀🚀🚀圣诞快乐,系列有🚀了'))
// console.log(clipTitle3 ('🎅🎄🎁❤️🚀❤️圣诞快乐,系列有🚀了'))
// 逗号后面字符没有了

function clipTitle3 (title) {
  let strList = [...title]
  let len = strList.length
  let res = title

  if (len > 15) {
    let mid = Math.floor(len / 2) - 1
    // 检测字符是否为emoji表情或标点
    let signCheck = /(\ud83c[\udf00-\udfff])|(\ud83d[\udc00-\ude4f\ude80-\udeff])|[\u2600-\u2B55]|[,;:——……]/
    if (signCheck.test(strList[mid])) {
      res = `${strList.slice(0, 6).join('')}...${strList.slice(len - 6).join('')}`
    } else {
      let leftDot = 0, rightDot = len - 1
      for (let i = mid - 1; i > -1; i--) {
        if (signCheck.test(strList[i])) {
          leftDot = i
          break
        }
      }

      for (let i = mid + 1; i < len; i++) {
        if (signCheck.test(strList[i])) {
          rightDot = i
          break
        }
      }

      if (leftDot === 0 && rightDot === len - 1) {
        res = `${strList.slice(0, 6).join('')}...${strList.slice(len - 6).join('')}`
      } else if (rightDot - mid < mid - leftDot) {
        let rightLen = len - 1 - rightDot // 右边字符长度
        res = `${strList.slice(0, 12 - rightLen).join('')}...${strList.slice(rightDot + 1).join('')}`
      } else {
        let rightLen = 12 - leftDot // 右边字符长度
        res = `${strList.slice(0, leftDot).join('')}...${strList.slice(leftDot + 1, leftDot + 1 + rightLen).join('')}`
      }
    }
  }

  return res
}
liyongleihf2006 commented 4 years ago
function titleFormat(title){
    return title.trim().replace(/([^]{6})(?:[^]+)(?=[^]{6})/,function($0,$1){
        return $1+"…";
    })
}
console.log(titleFormat("这是六个字符"));
console.log(titleFormat("这是六个字符这是六个字符"));
console.log(titleFormat("这是六个字符a这是六个字符"));
console.log(titleFormat("这是六个字符这是六个字符这是六个字符"));
console.log(titleFormat("    这是带空格的字符            字符   "));
function filenameFormat(filename){
    return filename.trim().replace(/([^]+)([^]\.\w+)/,function($0,$1,$2){
        //获取总长度
        var totalLen = $0.length;
        if(totalLen<=15){
            return $0;
        }
        //获取后缀的长度
        var suffixLen = $2.length;
        //获取除了后缀和省略号以外还需要的长度
        var prefixLen = 12 - suffixLen;
        return $1.slice(0,prefixLen)+"…"+$2;
    })
}
console.log(filenameFormat('这是个文件名.jpg'));
console.log(filenameFormat('这是个文件名这是个文件.jpg'));
console.log(filenameFormat('这是个文件名这是个文件名这是个文件名.jpg'));
console.log(titleFormat2('🎅🎄🎁❤️🚀圣诞快乐,系列有9了'));
console.log(titleFormat2('🎅🎄🎁❤️🚀大家圣诞快乐,系列有9了'));
console.log(titleFormat2('🎅🎄🎁❤️🚀大家圣诞快乐,这个系列有9了'));   // zxx: 这个打点应该在逗号位置
console.log(titleFormat2('这是六个字符这是六个字符这是六个字符'));
function titleFormat2(title){
    var reg = /[,;:——……]/g;
    var arr = [];
    //将所有的完整字符以及是否是emoji放到一个数组当中
    for (var i=0, chr; i < title.length; i++) {
        [chr, i,isEmoji] = getWholeCharAndI(title, i);
        arr.push([chr,isEmoji]);
    }
    //如果长度小于等于15;原样返回
    if(arr.length<=15){
        return title;
    }
    //判断有没有emoji和指定的逗号等字符
    var isSimple = arr.every(function(item){
        return !isComplex(item);
    })
    //如果没有emoji和指定的逗号等字符,那么使用一中的方式返回
    if(isSimple){
        return title.trim().replace(/([^]{6})(?:[^]+)(?=[^]{6})/,function($0,$1){
            return $1+"…";
        })
    }
    var l = Math.floor((arr.length-1)/2);
    var r = Math.ceil((arr.length-1)/2);
    var toL = true;
    while(toL?!isComplex(arr[l]):!isComplex(arr[r])){
        toL?l--:r++;
        toL = !toL;
    }
    var pos = toL?l:r;
    //下面使用11的原因是因为省略号是表示3个字符,然后最开头要有一个字符所以 15 - 3 - 1 = 11; 
    //先获取特殊字符右侧的完整字符长度,若是特殊字符右侧的完整字符大于等于11个,那么右侧就保留11个完整字符,左侧保留第一个完整字符
    //若是右侧的完整字符数量小于11个,那么左侧就保留12减去右侧完整字符的数量
    var rightLen = arr.length - pos - 1;
    if(rightLen>=11){
        return arr[0][0] + "…" + arr.slice(-11).map(item=>item[0]).join("");
    }else{
        var leftLen = 12 - rightLen;
        return arr.slice(0,leftLen).map(item=>item[0]).join("")+"…"+arr.slice(pos+1).map(item=>item[0]).join("");
    }
    function isComplex(item){
        return item[1]||reg.test(item[0]);
    }
}
//我从mdn中找的获取整个字符的方法,顺便改了一下,返回的第三个表示是否是emoji字符
function getWholeCharAndI (str, i) {
  var code = str.charCodeAt(i);

  if (isNaN(code)) {
    return ''; // Position not found
  }
  if (code < 0xD800 || code > 0xDFFF) {
    return [str.charAt(i), i]; // Normal character, keeping 'i' the same
  }

  // High surrogate (could change last hex to 0xDB7F to treat high private 
  // surrogates as single characters)
  if (0xD800 <= code && code <= 0xDBFF) { 
    if (str.length <= (i+1))  {
      throw 'High surrogate without following low surrogate';
    }
    var next = str.charCodeAt(i+1);
      if (0xDC00 > next || next > 0xDFFF) {
        throw 'High surrogate without following low surrogate';
      }
      return [str.charAt(i)+str.charAt(i+1), i+1,true];
  }
  // Low surrogate (0xDC00 <= code && code <= 0xDFFF)
  if (i === 0) {
    throw 'Low surrogate without preceding high surrogate';
  }
  var prev = str.charCodeAt(i-1);

  // (could change last hex to 0xDB7F to treat high private surrogates
  // as single characters)
  if (0xD800 > prev || prev > 0xDBFF) { 
    throw 'Low surrogate without preceding high surrogate';
  }
  // Return the next character instead (and increment)
  return [str.charAt(i+1), i+1]; 
}
julenwang commented 4 years ago
//1
function format1(title) {
  if (typeof title === 'string' && title.length > 15) {
    return `${title.slice(0, 6)}...${title.slice(
      title.length - 7,
      title.length - 1
    )}`;
  }
  return title;
}
//2
function format2(fileName) {
  if (fileName.length > 15) {
    const end = '...' + fileName.substring(fileName.lastIndexOf('.') - 1);
    return end.padStart(15, fileName);
  }
  return fileName;
}
//3 不会,等开课
wingmeng commented 4 years ago

第 1 题

let title = '这是最后一期了,感谢同学们的一路相伴,更要向为47期小测耗费心血的张老师致敬!';

if (title.length > 15) {
  title = title.replace(/^(.{6}).*(.{6})$/, '$1...$2');
}

console.log(title);  // "这是最后一期...张老师致敬!"

第 2 题

let filename = 'weixin_20191221232646.jpg';

if (filename.length > 15) {
  filename = filename.replace(/^(.+)(\.\w+)$/, (_, $1, $2) => {
    let tail = '...' + $1.substr(-1) + $2;
    return $1.substr(0, tail.length - 1) + tail;
  });
}

console.log(filename);  // "weixin_...6.jpg"

第 3 题

思路基本理顺了,但实现上仍然有 bug,待进一步优化 :joy:

function formatTitle(titleStr) {
  // emoji 的 unicode 范围实在是太繁杂了,既有双字节的,还有单字节的
  // 下面的 emoji 正则表达式参考自 lodash@4.16.6
  const regexp_emoji = new RegExp('(' +
    '(?:[\u2700-\u27bf]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff])' +
    '[\ufe0e\ufe0f]?' +
    '(?:[\u0300-\u036f\ufe20-\ufe23\u20d0-\u20f0]|\ud83c[\udffb-\udfff])?' +
    '(?:\u200d(?:[^\ud800-\udfff]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff])' +
    '[\ufe0e\ufe0f]?' +
    '(?:[\u0300-\u036f\ufe20-\ufe23\u20d0-\u20f0]|\ud83c[\udffb-\udfff])?)*' +
  ')', 'g');
  const regexp_symbol = /[,;:……——]/;
  const emojiArr = titleStr.match(regexp_emoji);
  // 将 title 字符串打散成数组,避免双字节 emoji 字符的影响(每个 emoji 算1个字符)
  const titleArr = titleStr.split(regexp_emoji).reduce((arr, s) => {
    if (emojiArr && emojiArr.includes(s)) {
      arr.push(s)
    } else {
      arr = arr.concat(s.split(''))
    }

    return arr;
  }, []);

  if (titleArr.length > 15) {
    const half = Math.floor(titleArr.length / 2);
    let left = titleArr.slice(0, half);
    let right = titleArr.slice(half);
    let leftPoint = 0;
    let rightPoint = 0;

    // 从中心向两端查找第一个 emoji 或中文标点出现的指针位置
    left.some((_, idx, arr) => {
      const index = arr.length - 1 - idx;
      if (emojiArr && emojiArr.includes(arr[index]) || regexp_symbol.test(arr[index])) {
        leftPoint = index + 1;
        return true;
      }
    });
    right.some((item, idx) => {
      if (emojiArr && emojiArr.includes(item) || regexp_symbol.test(item)) {
        rightPoint = idx;
        return true;
      }
    });

    if (leftPoint === 0 && rightPoint === 0) {
      return titleStr.replace(/^(.{6}).*(.{6})$/, '$1...$2');
    }

    let diffValue;

    if (rightPoint > left.length - leftPoint) {
      diffValue = 15 - left.length - 3;  // 差值
      left = left.join('');
      right = right.slice(0, rightPoint).join('') + '...' +
        right.slice(right.length - 1 - rightPoint).join('');
    } else {
      diffValue = 15 - right.length - 3;  // 差值
      left = left.slice(0, left.length - 1 - diffValue).join('') + '...' +
        left.slice(leftPoint).join('');
      right = right.join('');
    }

    return left + right;
  }

  return titleArr.join('');
}
livetune commented 4 years ago
function strToArr(str) {
  const arr = str.split('')
  const res = []
  for (let i = 0; i < arr.length - 1; i++) {
    const tmps = arr[i] + arr[i + 1]
    if (String.fromCodePoint(tmps.codePointAt()) === tmps) {
      res.push(tmps)
      i++;
    } else {
      res.push(arr[i])
      if (i === arr.length - 2) {
        res.push(arr[i + 1])
      }
    }
  }
  return res
}

//1.

function titleEllipsis(str = "") {
  const strArr = strToArr(str)
  return strArr.length > 15 ? strArr.slice(0, 6).join('') + '...' + strArr.slice(-6).join('') : str;
}

// 2.
function fileEllipsis(str = "") {
  const file = str.match(/^(.+)(\..+)$/);
  if (file) {
    const fileName = file[1];
    const extName = file[2];
    if (fileName.length <= 15) {
      return str;
    }
    return (
      fileName.replace(
        new RegExp(`^(.{${11 - extName.length}})(.+)(.)$`),
        "$1...$3"
      ) + extName
    );
  }
  return titleEllipsis(str);
}
// 3.
function emojiEllipsis(str) {
  strArr = strToArr(str)
  if (strArr.length > 15) {

    let left = strArr.slice(0, 6)
    let right = strArr.slice(-6)
    const filter = (arr, index, type = "pop") => {
      if (arr[index].match(/(^[^0-9a-zA-Z\u4e00-\u9fa5]+)$/)) {
        arr[type]()
        return true
      } else {
        return false
      }
    }
    filter(left, 5, 'pop')
      && filter(left, 4, 'pop')
      && filter(left, 3, 'pop')

    left.length === 6 && filter(right, 0, 'shift')
      && filter(right, 1, 'shift')
      && filter(right, 2, 'shift')
    if (left.length !== 6) {
      return left.join('') + '...' + strArr.slice(-1 * (13 - (6 - left.length))).join('')
    } else if (right.length !== 6) {
      return strArr.slice(0, 13 - (right.length)).join('') + '...' + right.join('')
    }
  }
  return titleEllipsis(str);
}

console.log(titleEllipsis('在这里祝大家圣诞快乐系列有了9!'))
console.log(fileEllipsis('sdljaskljd_Sadaisjdla.jpg'))
console.log(emojiEllipsis('🎅🎄🎁❤️🚀圣诞快乐,系列有9了'))
console.log(emojiEllipsis('🎅🎄🎁❤大家圣诞快乐,系列有9了'))
console.log(emojiEllipsis('在这里祝大家圣诞快乐系列有了9!'))
rayj1993 commented 4 years ago
// 第一题
function ellipsisStr1(str) {
    let len = str.length
    if (len > 15) {
        return str.substr(0, 6) + '...' + str.substr(len - 6, len)
    }
    return str
}
console.log(ellipsisStr1('asdasdas12312312d'))
// 第二题
// ellipsisStr2('weixin_2938384.v.123.pptx');有bug
function ellipsisStr2(str) {
    let len = str.length
    if (len > 15) {
        let endStr = str.match(/\w?\.\w+/gi)[0]
        let benginStr = 15 - 3 - endStr.length
        return str.substr(0, benginStr) + '...' + endStr
    }
    return str
}
juzhiqiang commented 4 years ago
// 第一题
function spliceTitle(str){
    var len = str.length;
    return len > 15 ? `${str.substr(0,6)}...${str.substr(len-6,len)}` : str ; 
}

// 第二题
function legalFileName(str){
    var len = str.length;
    if(len < 15) return str ;
    var lastStr = str.substr(str.lastIndexOf('.')-1,len);
    var lastLen = lastStr.length;
    return `${str.substr(0,(12 - lastStr.length))}...${lastStr}`
}

// 第三题
function cenTitle(str){
    var len = str.length;
    if(len < 15) return str ;
    var emojiReg = /(\ud83c[\udf00-\udfff])|(\ud83d[\udc00-\ude4f])|(\ud83d[\ude80-\udeff])/g;
    var cen = Math.floor(len / 2);
    var last = len - 12
   // 对emoji 处理有些问题
    if(emojiReg.test(str[cen-1])){
        return last > cen ? `${str.substr(0,1)}...${str.substr(cen+(last-cen),len)}` : `${str.substr(last-cen,cen)}...${str.substr(cen,len)}`
    }else{
         return `${str.substr(0,6)}...${str.substr(len-6,len)}`
    }
}
ziven27 commented 4 years ago

第一题

const title = '🎅🎄🎁❤️🚀圣诞快乐,系列有9了';
const getDotString = function (strInput) {
    if (strInput.length > 15) {
        return strInput.slice(0, 6) + '...' + strInput.slice(-6);
    }
    return strInput;
};
const strDot = getDotString(title);

console.log(strDot);

第二题

// 'weixin_20191221232646.v1.jpg' 有问题
const filename = 'weixin_20191221232646.jpg';
const getDotFileString = function (strInput) {
    if (strInput.length > 14) {
        const dotAtIndex = strInput.indexOf('.');
        const numAppendLen = strInput.length - dotAtIndex + 1;
        const numPreLen = 15 - numAppendLen - 3;
        return strInput.slice(0, numPreLen) + '...' + strInput.slice(-1 * numAppendLen);
    }
    return strInput;
};
const strFilename = getDotFileString(filename);

console.log(strFilename);

第三题

const title1 = '🎅🎄🎁❤️👋🚀圣诞快乐,系列有9了';
const title2 = '🎅🎄🎁❤️大家圣诞快乐,系列有9了';
const title3 = '在这里祝大家圣诞快乐系列有9!';

// 是否为特殊字符
// 没有确定好 中文标点 unicode 范围,为实现打点逻辑这里用的数组代替
const isSpecialCode = function (char) {
    const znCodeArray = [',', ';', ':', '——', '…', '!'];
    if (znCodeArray.indexOf(char) > -1) {
        return true;
    }
    return false;
};
// 是否为emoji
// 没有确定好 emoji unicode 范围,为实现打点逻辑这里用的数组代替
const isEmoji = function (char) {
    const emojiArray = ['🎅', '🎄', '🎁', '❤️', '🚀', '👋'];
    if (emojiArray.indexOf(char) > -1) {
        return true;
    }
    return false;
};

// 打点
const getSmartDotString = function (strInput) {
    if (strInput.length < 15) {
        return strInput;
    }
   // 中心点位置
    const midIndex = Math.floor(strInput.length / 2);
    let specialMatch = [];
    for (let i = 0; i < strInput.length; i++) {
        const thisChar = strInput.charAt(i);
        const emojiChar = strInput.slice(i, i + 2);
        if (isSpecialCode(thisChar)) {
            specialMatch.push({
                char: thisChar,
                index: i,
                len2Mid: Math.abs(i - midIndex)
            });
        } else if (isEmoji(emojiChar)) {
            specialMatch.push({
                char: emojiChar,
                index: i,
                len2Mid: Math.abs(i - midIndex) + 1
            });
            // 是 emoji 自增1
            i++;
        }
    }
    if (specialMatch.length > 0) {
        // 基于距离中心点距离排序
        const matchItem = specialMatch.sort(function (a, b) {
            return a.len2Mid - b.len2Mid;
        })[0];
        // 整条线点比例按照如下逻辑排列
        // 0 => starIndex => matchItem.index => endIndex => strInput.length
        if (matchItem.index !== 0 && matchItem.index !== strInput.length - 1) {
            const startIndex = Math.floor(12 * matchItem.index / strInput.length);
            const endIndex = startIndex + strInput.length - 12;
            const endLen = strInput.length - endIndex;
            return strInput.slice(0, startIndex) + '...' + strInput.slice(-1 * endLen);
        }
    }
    return strInput.slice(0, 6) + '...' + strInput.slice(-6);
};
console.log(getSmartDotString(title1));
console.log(getSmartDotString(title2));
console.log(getSmartDotString(title3));
NeilChen4698 commented 4 years ago

1.

title.replace(/^(.{6}).{3,}(.{6})$/, function(str,prefix,suffix) {
    return prefix + '...' + suffix;
});

2.

title.replace(/^(.*)(.{1}\..+)$/, function(str,prefix,suffix) {
    if (str.length <= 15) {
        return str;
    } else {
        var s = '...' + suffix;
        return s.length >= 15  ? s : (prefix.substring(0, 15 - s.length) + s);
    }
});

3.

function format(val) {
    var max = 15;
    if (val.length <= max) {
        return val;
    }
    var reg = /\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]|[\uff0c\uff1b\uff1a\u2014\u2026]/;
    var result = Array.from(val.matchAll(reg));
    if (result.length === 0 || (result.length === 1 && (result[0].index === 0 || result[0].index === val.length - 1))) {
        return val.replace(/^(.{6}).{4,}(.{6})$/, function(str,prefix,suffix) {
            return prefix + '...' + suffix;
        })
    } else {
        for (var i = parseInt(val.length / 2) - 1; i >= 0; i--) {
            if (val[i].match(reg)) {
                var suffix = '...' + val.substring(i + 1);
                var prefixLen = max - suffix.length;
                return (prefixLen > 0 ? val.substring(0,prefixLen) : '') + suffix;
            } else if (val[val.length - 1 - i].match(reg)) {
                var prefix = val.substring(0,val.length - 2 - i) + '...';
                var suffixLen = max - prefix.length;
                return prefix + (suffixLen > 0 ? val.substring(val.length - suffixLen,val.length) : '');
            }
        }

    }
}
nanaSun commented 4 years ago
//  一
function eclipseText(str){
  if(typeof str !== "string"){
    return str
  }
  let strlen =  str.length;
  return strlen<15?str:str.slice(0,6)+"..."+str.slice(strlen-6,strlen)
}

//  二
function eclipseFileText(str){
  if(typeof str !== "string"){
    return str
  }

  let strlen =  str.length;

  if(strlen<15){
    return str;
  }

  const extRegex = /\.[^.\\/:*?"<>.|\r\n]+$/ig;
  const ext = (str.match(extRegex)||[]).join("");
  const extLen = ext.length;

  if(extLen>0){
    return str.slice(0,12-extLen-1)+"..."+str.slice(strlen-extLen-1,strlen)
  }else{
    return str.slice(0,6)+"..."+str.slice(strlen-6,strlen)
  }
}

//  三
function eclipseSpecialText(str){
  if(typeof str !== "string"){
    return str
  }
  let strlen =  str.length;
  if(strlen<15){
    return str;
  }

  const emojiRegex=/[\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]|\u3002/ig;
  const emoji = str.match(emojiRegex)||[]
  const emojiLen = emoji.length;

  if(emojiLen>0){
    // 用于判断emoji
    const arr =[...str]
    strlen = arr.length; 
    let count = Math.floor(strlen/2)-1
    let preCount = count;
    let afterCount = count+1;
    let dotIndex = 0
    for(let i=0;i<count;i++){
      if(arr[preCount].length>1||/\uff1b|\uff0c|\uff1a|\u201c|\u201d|\uff08|\uff09|\u3001|\uff1f|\u300a|\u300b/.test(arr[preCount])){
        dotIndex = preCount
        break
      }
      if(arr[afterCount].length>1||/\uff1b|\uff0c|\uff1a|\u201c|\u201d|\uff08|\uff09|\u3001|\uff1f|\u300a|\u300b/.test(arr[afterCount])){
        dotIndex = afterCount
        break
      }
      preCount--;
      afterCount++;
    }
    if(dotIndex>3&&dotIndex<strlen-3){
      return arr.slice(0,dotIndex-2).join("")+"..."+arr.slice(dotIndex+1,strlen).join("")
    }else{
      return arr.slice(0,6).join("")+"..."+arr.slice(strlen-6,strlen).join("")
    }
  }else{
    return str.slice(0,6)+"..."+str.slice(strlen-6,strlen)
  }
}

// 纯文字
console.log( eclipseText("啦啦啦啦啦我是,小当家"))
console.log( eclipseText("啦啦啦啦啦我是卖报的小当家你猜我猜大家猜"))

// file后缀
console.log( eclipseFileText("啦啦啦啦小当家.jpg.jpg"))
console.log( eclipseFileText("abcdefg啦啦啦啦啦我是卖报的小当家你猜我猜大家猜.jpeg"))
console.log( eclipseFileText("abcdefg啦啦啦啦啦我是卖报的小当家你猜我猜大家猜.jpg"))

// 带有表情
console.log( eclipseSpecialText("🎅🎄🎁❤️🚀圣诞快乐,系列有9了"));
console.log( eclipseSpecialText("🎅🎄💗🎁大家圣诞快乐,系列有9了"));
console.log( eclipseSpecialText("大家圣诞快乐乐乐乐乐乐系列有9了"));
GCGligoudan commented 4 years ago

最后一期打卡

// 1.
let title = '本期关于字符打点处理,是下半学期最后一期。';

function clipTitle(str) {
  if (str.length > 15) {
    return str.slice(0, 6) + '...' + str.slice(-6);
  }
  return str;
}
console.log(clipTitle(title));

// 2.
// filename = 'weixin_201912212326.v46.jpg' 有 bug
let filename = 'weixin_20191221232646.jpg';

function clipFilename(str) {
  let fileName = str.split('.')[0];
  let fileType = str.split('.')[1];
  if (str.length > 15) {
    return fileName.slice(0, 15 - fileType.length - 2 - 3) + '...' + fileName.slice(-1) + '.' + fileType;
  }
  return str;
}
console.log(clipFilename(filename));

// 3. 
CMYK99 commented 4 years ago

1.

var title = '这是一个超级长长长长长长的标题'
title = title.replace(/^(.{6}).{4,}(.{6})$/, '$1...$2')
console.log(title)

2.

var title = 'weixin_20191221232646.jpg'
if (title.length > 15) {
title = title.replace(/^.+(.\.[^\.]+$)/, (name, suffix) => {
return name.substr(0, 15 - suffix.length - 3) + '...' + suffix
})
}
console.log(title)

3.

Forx-Js commented 4 years ago
/**
 * 
 * @param {string} title 
 * @returns {string}
 */
const clipString = title => {
  const titleArray = [...title], // 将字符串转成数组,主要应对后续emoji长度问题
    length = titleArray.length, // 获取字符串长度
    maxLength = 15, // 允许的字符长度
    isLong = length > maxLength,
    fileNameReg = /\S\.[\w\d]+$/,
    isFileName = fileNameReg.test(title);
  if (!isLong) return title //短字符串
  else if (isFileName) {
    /*第二题*/
    const lastIndex = title.match(fileNameReg).index; // x.xxx 的下标
    return title.substr(0, maxLength - 3 - length + lastIndex) + '...' + title.slice(lastIndex)
    /*第二题 结束*/
  } else {
    /* 第一题 */
    return title.substr(0, 6) + '...' + title.slice(-6)
    /* 第一题 结束 */
  }
}

/**更新:添加测试**/
const titleList = [
  '我只是一段很短的文字',
  '我是一段很长很长很长很长很长的文字',
  '我是一个文件.txt',
  '我是一个作者用记事本写出来的长达12000多行的.jsx',
  '🎅🎄🎁❤️🚀圣诞快乐,系列有9了'
];
console.log(
  titleList.map(clipString)
) 

第三题感觉味不对,怎么做都别扭,先空着

sghweb commented 4 years ago
// 第一题
function cutstr(str,starLen,endLen){
  let strStart = str.substring(0,starLen)
  let strEnd = str.substring(str.length-endLen,str.length)
  return {
    strStart:strStart,
    strEnd:strEnd
  }
}
function ellipsisTitle(str){
  if(str.length<=15){
    return str;
  }
  let {strStart,strEnd} = cutstr(str,6,6)
  return strStart+'...'+strEnd
}
//第二题
function ellipsisFileName(filename){
  if(filename.length<=15){
    return filename
  }
  let pos = filename.lastIndexOf('.')
  let len = filename.length
  let postfix = filename.substring(pos+1,len)
  let filenameHead = filename.substring(0,pos)
  let {strStart,strEnd} = cutstr(filenameHead,10-postfix.length,1)
  return `${strStart}...${strEnd}.${postfix}`
}
//第三题
function isEmojiCharacter(substring) {
  for ( var i = 0; i < substring.length; i++) {
    var hs = substring.charCodeAt(i);
    if (0xd800 <= hs && hs <= 0xdbff) {
        if (substring.length > 1) {
            var ls = substring.charCodeAt(i + 1);
            var uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
            if (0x1d000 <= uc && uc <= 0x1f77f) {
                return true;
            }
        }
    } else if (substring.length > 1) {
        var ls = substring.charCodeAt(i + 1);
        if (ls == 0x20e3) {
            return true;
        }
    } else {
        if (0x2100 <= hs && hs <= 0x27ff) {
            return true;
        } else if (0x2B05 <= hs && hs <= 0x2b07) {
            return true;
        } else if (0x2934 <= hs && hs <= 0x2935) {
            return true;
        } else if (0x3297 <= hs && hs <= 0x3299) {
            return true;
        } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030
                || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b
                || hs == 0x2b50) {
            return true;
        }
    }
  }
}
function specilWord(str){
  let patt = /[-,.?:;'"!`]|(-{2})|(\.{3})/g
  if(patt.test(str)||isEmojiCharacter(str)){
    return true
  }
}
function ellipsisTit(str,key){
  if(str.length<=15){
    return str
  }
  let strArr = []
  if(key){
    strArr = str.split(key)
    if(strArr[0].length>=6&&specilWord(strArr[0])){
       return strArr[0].substring(0,6)+'...'+key+strArr[1]
    }else{
      return strArr[0]+key+'...'+strArr[1].substring(strArr[1].length-6)
    }
  }else{
    return ellipsisTitle(str)
  }
}
zengqingxiao commented 4 years ago

// 第一题

    /**
     * 判断字符串长度
     * @param [String] 检查的字符串  
     */
    function handleJudgeStringLength(srt) {
      return srt.length > 15 ? true : false
    }

    var title = 'zqx真的真的是又帅又可以还真的超级超级聪明'
    /**
     * 修改字符串
     * @param [String] 修改的字符串  
     */
    function handleAlterTitle(str) {
      if (handleJudgeStringLength(str)) {
        return str.substring(0, 6) + '...' + str.substring(str.length - 6, str.length)
      } else {
        return str
      }
    }
    console.log(handleAlterTitle(title))

//第二题

// zxx: 有bug
    var filename = 'zqx真的真的是又帅又可以还真的超级超级聪明.jpg'
    function handleAlterFilename(str) {
      if (handleJudgeStringLength(str)) {
        var reg = /([\s\S]+)\.([\s\S]+)$/g
        var endStr = str.replace(reg, function (all, $1, $2) {
          var str_1 = $1.substring(0, (15 - ($2.length + 2))) + '...' + $1.substring($2.length - 1, 1) + '.' + $2
          return str_1
        })
        return endStr
      } else {
        return str
      }

    }
    console.log(handleAlterFilename(filename), 'str的值-------')

//第三题 今天晚上跟新 尝试下

    function handleJudgeSymbol(str) {
      console.log(str, 'str的值------------')
      var reg = /(\ud83c[\udf00-\udfff])|(\ud83d[\udc00-\ude4f\ude80-\udeff])|[\u2600-\u2B55]|([,;:—……])/g
      // console.log(reg.test(str), '判断是否存在')
      return reg.test(str)
    }
    handleJudgeSymbol('🎅')
zy017 commented 4 years ago
// 1
function transTitle(s) {
    return s.length > 15 && s.replace(/(?<=^.{6}).*(?=.{6}$)/, "...") || s
}
var title1 = '123456'
var title2 = '123456123123456'
var title3 = '123456123456123456'
console.log(transTitle(title1))
console.log(transTitle(title2))
console.log(transTitle(title3))

// 2
// zxx: 有bug,如var filename = 'weixin_201912212326.v46.jpg'
function transFilename(s) {
    if (s.length > 15) {
        // var len = 10 - s.match(/(?<=\.).*$/)[0].length
        // var reg = eval(`/(?<=^.{${len}}).*(?=.\\..*$)/`)
        // 修改:
        var len = 10 - s.match(/(?<=\.)[^\.]*$/)[0].length
        var reg = eval(`/(?<=^.{${len}}).*(?=.\\.[^\\.]*$)/`)
        return s.replace(reg, "...")
    }
    return s
}
var filename = 'weixin_20191221232646.jpg'
console.log(transFilename(filename))

// 3
function transEmoji(s) {
    var reg = /(,|:|;|——|……|(\ud83c[\udf00-\udfff])|(\ud83d[\udc00-\udfff])|(\ud83d[\udd00-\udfff])|[\u2600-\u27ff])\ufe0f?|./g
    var regEmoji = /(,|:|;|——|……|(\ud83c[\udf00-\udfff])|(\ud83d[\udc00-\udfff])|(\ud83d[\udd00-\udfff])|[\u2600-\u27ff])\ufe0f?/
    var a = s.match(reg)
    var len = a.length
    if (len > 15) {
        var i = parseInt(len / 2 )
        var start = a.slice(0, i)
        var startReverse = start.reverse()
        var end = a.slice(i)
        var index1 = startReverse.findIndex(item => regEmoji.test(item))
        var index2 = end.findIndex(item => regEmoji.test(item))
        // 打点index 及 打点方向
        var index, to = 0
        if ((index1 <= index2 || index2 === -1) && index1 !== -1 ) {
            index = i - index1 - 1
            if (index >= 3) {
                if (regEmoji.test(a[index - 1])) {
                    to = -1
                } else {
                    to = 1
                }
            } else {
                to = 0
            }

        } else if ((index1 > index2 || index1 === -1) && index2 !== -1) {
            index = i + index2
            if (index < len - 3) {
                if (regEmoji.test(a[index + 1])) {
                    to = 1
                } else {
                    to = -1
                }
            } else {
                to = 0
            }
        }
        if (to > 0 && index < 11) {
            return a.slice(0, index).join('') + '...' + a.slice(index - 12).join('')
        } else if (to < 0 && len - index - 1 < 11) {
            return a.slice(0, 12 - (len - index - 1)).join('') + '...' + a.slice(index + 1).join('')
        } else {
            return a.slice(0, 6).join('') + '...' + a.slice(-6).join('')
        }
    }
    return s
}
var title = '🎅🎄🎁❤️❤️🚀圣诞快乐,系列有9了'
var title1 = '🎅🎄🎁❤️大家圣诞快乐,系列有9了'
var title2 = '大家圣诞快❤️乐cccccccccc系列有9了'
var title3 = '🎅🎄🎁ddddddd圣诞快乐,❤️系列有测了'
var title4 = '🎅🎄dddddd快乐系列有测了🎄🎁❤️'
console.log('title------', transEmoji(title))
console.log('title1------', transEmoji(title1))
console.log('title2------', transEmoji(title2))
console.log('title3------', transEmoji(title3))
console.log('title4------', transEmoji(title4))
silverWolf818 commented 4 years ago
//第一题
function ellipsis(str){
    if(str.length > 15){
        return str.substr(0,6) + '...' + str.substr(-6);
    }else{
        return  str;
    }
}

//第二题
function fileEllipsis(filename){
    if(filename.length > 15){
        var arr = filename.split('.');
        var tail = arr[1].length + 2;
        var head = 15 - 3 - tail;
        return filename.substr(0,head) + '...' + filename.substr(-tail);
    }else{
        return filename;
    }
}
//zxx: fileEllipsis('weixin_298383784.v.23.jpeg'); bug
lifelikejuly commented 4 years ago

var title = '🎅🎄🎁❤️🚀圣诞快乐,系列有9了'; var fileName = "weixin_201912221234567av.jpg"; var title2 = '🎅🎄🎁❤️🚀大家圣诞快乐,系列有9了'; var title3 = '在这里祝大家圣诞快乐,系列有9了';

zhangxinxu commented 4 years ago

本期要点:

  1. 使用substr,或者slice都可以。
  2. 'weixin_20191221232646.jpg'以及'weixin_201912212326.v46.jpeg'都需要满足。字符裁剪处理,没有看到特别的技巧。JaimeCheng的实现还是挺简洁的,可以参考下。
  3. 把字符分成前后两部分,A B遍历,匹配。Despair-lj AsyncGuo XboxYan 3人实现可以有兴趣线下研究下。