First, explain
Chinese string interception is two bytes, a alphanumeric character, Common taken
substr () whether Chinese or letters are taken by one, the processing now taken string containing characters
Second, examples:
abc def Bi fruit
const test = 'ab Bi fruit DEF' ; console.log(this.Substr(test, 2, 6)); console.log(this.Substr(test, 0, 3));
Third, the code
// string interception process contains Chinese, str need to intercept the string, start start position of interception, n intercept length Substr (STR, start, n) { // eslint disable-Line- IF (str.replace (/ [\ u4e00 . - \ u9fa5] / G, '**') length <= n-) { return STR; } years as = 0 ; tmpStr the let = '' ; for (I = Start the let; I <str.length; I ++) { // iterate string IF (/[\u4e00-\u9fa5]/.test(str[i])) { // Chinese two bytes in length len + = 2 ; } else { only + = 1 ; } if (len > n) { break; } else { tmpStr += str[i]; } } return tmpStr; }