Single-line display in the front end can be easily done with CSS; But in the actual development there will be a lot of multi-line omission, in the Internet to find a lot of ways can not be very good to solve the problem. The main questions are:
- Chinese and English can’t simply handle strings with arbitrary string lengths: 100 Chinese characters might be enough, but 100 English characters might be just a few words
- Each Chinese and English width is different and cannot be achieved by positioning a simple cover with three dots behind the text
So what’s our solution? Our solution is to intercept the string by judging the character’s byte; A Chinese character is 2 bytes, and an English character is 1 byte. Then during the screen display, we find that the width of two English characters is almost the same as the width of a Chinese character (not exactly the same, there will be some floating), so we can intercept the string according to the number of bytes. The implementation code is as follows:
const substrByByte = function (str, num) { let bytesCount = 0; for (let i = 0; i < str.length; i++) { let c = str.charAt(i); if (/^[\u0000-\u00ff]$/.test(c)) { bytesCount += 1; } else { bytesCount += 2; } if (bytesCount > num) { return str.substr(0, i) + '... ' } else if (bytesCount === num) { return str.substr(0, i + 1) + '... ' } } return str }Copy the code
Traversal string, if it is Chinese, the number of bytes +2, non-Chinese +1; Then determine if the current number of bytes is greater than the number of bytes we need to intercept, if so, the ellipsis returns from the concatenation of string length I (remember I starts from 0); The concatenated ellipsis of (I + 1) is returned if it is equal to the character we want to truncate; If the number of bytes in the string is smaller than the number of bytes we want to intercept, we return the string directly. Here are two more examples to help you understand the appeal code:
SubstrByByte (' Hello 12 handsome ', 10) // Return: Hello 12 handsome... SubstrByByte (' Hello 123 handsome guy ', 10) // Return: Hello 123...Copy the code
In the second, we cut 10 bytes, with the 10th and 11th bytes being “handsome”. This triggers our bytesCount > num branch, which returns the string up to “handsome”
conclusion
Say not clear, if you have any questions, you can enter QQ group to ask me: 142681686