正则获取中英文长度

Posted chengyunshen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了正则获取中英文长度相关的知识,希望对你有一定的参考价值。

var str = ‘abcd来了efg‘; 
var len = str.match(/[^ -~]/g) == null ? str.length : str.length + str.match(/[^ -~]/g).length ;

截取固定长度的中英文字符串 (汉字算2个)

function sliceStr(str, len) {
				let i = 0,
					num = 0;
				let arr = str.split(‘‘)
				arr.some((item, index) => {
					if (/[u4E00-u9FA5]/.test(item)) {
						num += 2
					} else {
						num += 1
					}

					if (num === len || (/[u4E00-u9FA5]/.test(arr[index + 1])) && (num === (len - 1))) {
						i = index
						return true
					}
					return false
				})
				return str.slice(0, i + 1)
			}

以上是关于正则获取中英文长度的主要内容,如果未能解决你的问题,请参考以下文章