Runkit
Runkit
home page
user forum
new notebook
clone notebook
download notebook
support & documentation
log in
sign up
new notebook
help & feedback
clone this notebook
download this notebook
Sign In
Sign Up
RunKit + npm: grapheme-splitter
node v10.24.1
endpoint
share
tweet
var graphemeSplitter = require("grapheme-splitter") const 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; if ( emojiRex.test(arr[start - 1]) || chineseSymbol.indexOf(arr[start - 1]) > -1 ) { start -= 1; end -= 1; } else { handleLeft = false; } } else { end += 1; 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(''); } // 👩❤️💋👩 🏳️🌈🚀🌷 console.log(handleStr('🎅🎄🎁❤️🚀🌷圣诞快乐,系列有9了')); console.log(handleStr('🎅🎄🎁❤️大家圣诞快乐,系列有9了')); console.log(handleStr('在这里祝大家圣诞快乐系列有9!'));
Created from: https://npm.runkit.com/grapheme-splitter
Loading…
Clone and edit this document