-
-
Save minwe/9707e5945c2231437a1109fea53fbd72 to your computer and use it in GitHub Desktop.
截取指定长度的中英文混合字符串
This file contains 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
/** | |
* 截取指定长度的中英文混合字符串 | |
* @param {String} str 待截取的字符串 | |
* @param {Number} n 截取长度(中文字符为英文的 double) | |
* @return {String} 截取后的字符串 | |
*/ | |
function subString(str, n) { | |
var r = /[^\x00-\xff]/g; | |
var m; | |
if (str.replace(r, '**').length > n) { | |
m = Math.floor(n / 2); | |
for (var i = m, l = str.length; i < l; i++) { | |
if (str.substr(0, i).replace(r, '**').length >= n) { | |
return str.substr(0, i); | |
} | |
} | |
} | |
return str; | |
} |
Author
minwe
commented
Aug 22, 2017
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment