Skip to content

Instantly share code, notes, and snippets.

@minwe
Forked from roshanca/subString.js
Created July 27, 2017 08:13
Show Gist options
  • Save minwe/9707e5945c2231437a1109fea53fbd72 to your computer and use it in GitHub Desktop.
Save minwe/9707e5945c2231437a1109fea53fbd72 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;
}
@minwe
Copy link
Author

minwe commented Aug 22, 2017

var subMixedStr = function(str, n) {
  var r = /[^\x00-\xff]/g;
  if (str.replace(r, 'mm').length <= n) {
    return str;
  }

  var m = Math.floor(n / 2);
  var i = m;

  for (var i = m; i < str.length; i++) {
    var strLength = str.substr(0, i).replace(r, 'mm').length;

    if (strLength === n) {
      return str.substr(0, i);
    } else if (strLength > n) {
      return str.substr(0, i - 1);
    }
  }

  return str;
}

console.log(subMixedStr('撒打URL舒服得', 5));

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