Skip to content

Instantly share code, notes, and snippets.

@roshanca
Created December 5, 2012 09:35
Show Gist options
  • Save roshanca/4214281 to your computer and use it in GitHub Desktop.
Save roshanca/4214281 to your computer and use it in GitHub Desktop.
截取指定长度的中英文混合字符串
/**
* 截取指定长度的中英文混合字符串
* @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;
}
@jenawant
Copy link

jenawant commented Nov 14, 2023

TS版,替换了substr函数(后续将废弃)

`/**

  • 截取指定长度的中英文混合字符串
  • @param str 待截取的字符串
  • @param n 截取长度(中文字符为英文的 double)
  • @param ellipsis 省略号
  • @return 截取后的字符串
    */
    subString: (str: string, n: number, ellipsis: string = ""): string => {
    const r = /[^\x00-\xff]/g;
    let m;
if (str.replace(r, "**").length > n) {
  m = Math.floor(n / 2);

  for (let i = m, l = str.length; i < l; i++) {
    if (str.slice(0, i).replace(r, "**").length >= n) {
      return str.slice(0, i) + ellipsis;
    }
  }
}

return str;

}
`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment