JS split 分隔字符串区分中英文, 并且不截断英文

作者: tww844475003 分类: 前端开发 发布时间: 2022-12-10 21:34

背景

在我们日常开发中,经常会遇到分隔字符串的需求。如:echarts , 这个在可视化需求中使用非常调频的模块。坐标轴上由于太长,显示不友好,文字无法显示完整。普通的截取,无法区分中英文,也会把英文给截断,使英文失去了真实的意义。

费话不多说,直接上代码。

思路:

  • 先把字符按中文、英文单词分隔成数组
  • 然后按步长分隔字符串
    • 当前字符、单词长度大于步长时
var str = '你好 this is a boy 管理员 hello world meta chart utf-8 BudgetAllocationDirection charts;';
console.log(str)

splitStr(str, 8);
function splitStr(str, num) {
  // 第一步按中英文分隔字符
  const arr = [];
  let isENSubfix = true;
  for (let i = 0; i < str.length; i++) {
	const val = str[i];
	if (isCN(val) || val === ' ') {
	  arr.push(val);
	  isENSubfix = true;
	} else {
	  if (!isENSubfix) {
		arr[arr.length - 1] = `${arr[arr.length - 1]}${val}`;
	  } else {
		arr.push(val);
	  }
	  isENSubfix = false;
	}
  }
  console.log(arr);
  
  // 第二步按步长num截断字符
  const result = [];
  let temp = '';
  let tempLen = 0;
  for (let i = 0; i < arr.length; i++) {
	const val = arr[i];
	const len = getLen(val);
	
	// 如果长度大于 num
	if (len >= num) {
	  result.push(temp, val);
	  temp = '';
	  tempLen = 0;
	  continue;
	}

	if (tempLen + len < num) {
	  temp = `${temp}${val}`;
	  tempLen = getLen(temp);
	} else if (tempLen + len > num) {
	  result.push(temp);
	  temp = val;
	  tempLen = getLen(temp);
	} else {
	  result.push(`${temp}${val}`);
	  temp = '';
	  tempLen = 0;
	}

        // 以上条件都不符合,且数据 temp 有值是也需要保存,否则最后的数据会丢失
        if ((arr.length - 1 === i) && !!temp) {
          result.push(temp);
        }
  }
  console.log(result)
}

function getLen(str) {
  let len = 0;
  for (let i = 0; i < str.length; i++) {
	const val = str[i];
	if (isCN(val)) {
	  len += 2;
	} else {
	  len += 1;
	}
  }

  return len;
}

function isCN(val) {
  var re=/[^\u4E00-\u9FA5]/;
  if (re.test(val)) return false;
  return true;
}

输出结果

前端开发那点事
微信公众号搜索“前端开发那点事”

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注