Skip to content

Instantly share code, notes, and snippets.

@thinkgarden
Last active December 22, 2018 05:59
Show Gist options
  • Save thinkgarden/15ca125ce9ee6c8c0e5157a0e0d69b1e to your computer and use it in GitHub Desktop.
Save thinkgarden/15ca125ce9ee6c8c0e5157a0e0d69b1e to your computer and use it in GitHub Desktop.
[getStrFullLength.js] #js
const getStrFullLength = (str = '') =>
str.split('').reduce((pre, cur) => {
const charCode = cur.charCodeAt(0);
console.log(cur, charCode)
if(charCode >= 0&& charCode <= 128) {
return pre + 1;
} else {
return pre + 2;
}
}, 0)
const fullLength = getStrFullLength('你好 React!')
console.log(fullLength)
const cutStrByFullLength = (str = '', maxLength) => {
let showLength = 0;
return str.split('').reduce((pre, cur) => {
const charCode = cur.charCodeAt(0);
if (charCode >= 0 && charCode <= 128) {
showLength += 1;
} else {
showLength += 2;
}
if (showLength <= maxLength) {
return pre + cur;
}
return pre;
}, '');
};
const cutStr = cutStrByFullLength('React is a Good UI Componet!', 16)
console.log(cutStr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment