import isNum from './isNum';
import isStr from './isStr';
import isUdf from './isUdf';

/**
 * 给字符串指定位置打码
 * @param {string} string 需要打码字符串
 * @param {number} start 开始位置
 * @param {number} length 打码长度
 * @param {string} mask 打码符号，默认: *
 * @returns {string}
 *
 * @example
 * maskString('13878822602', 2);     // => '13*********'
 * maskString('13878822602', 3, 4);  // => '138****2602'
 * maskString('13878822602', 3, 4, x);  // => '138xxxx2602'
 */
function maskString(string, start, length, mask) {
  var str = String(string);
  if (!isNum(start)) return str;

  if (isStr(length)) {
    mask = length;
    length = undefined;
  }

  if (!isStr(mask)) mask = '*';
  var maskStr = str.substr(start, length).replace(/[^\u4e00-\u9fa5]/gm, mask).replace(/[\u4e00-\u9fa5]/gm, mask + mask);
  var prefix = str.substr(0, start);
  var suffix = isUdf(length) ? '' : str.substr(start + length);
  return prefix + maskStr + suffix;
}

export default maskString;
