Last active
August 29, 2015 14:12
-
-
Save oldj/fef849a579ec1603c29b to your computer and use it in GitHub Desktop.
从字符串左边截取n个字符
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
/** | |
* 从字符串 s 左边截取n个字符 | |
* 如果包含汉字,则汉字按两个字符计算 | |
* @see http://oldj.net/article/javascript-left-n-characters/ | |
* @param s {String} 输入的字符串 | |
* @param n {Number} | |
*/ | |
function strLeft(s, n) { | |
var s2 = s.slice(0, n), | |
i = s2.replace(/[^\x00-\xff]/g, "**").length; | |
if (i <= n) return s2; | |
i -= s2.length; | |
switch (i) { | |
case 0: return s2; | |
case n: return s.slice(0, n>>1); | |
default: | |
var k = n - i, | |
s3 = s.slice(k, n), | |
j = s3.replace(/[\x00-\xff]/g, "").length; | |
return j ? s.slice(0, k) + strLeft(s3, j) : s.slice(0, k); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment