Last active
December 22, 2018 05:59
-
-
Save thinkgarden/15ca125ce9ee6c8c0e5157a0e0d69b1e to your computer and use it in GitHub Desktop.
[getStrFullLength.js] #js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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