按字节截取字符串
在JS中,由于中文和英文是同等对待的,但有时候我们希望是一个中文按两个字节算,这就出现了按字节截取字符串的功能。下面列举了 2种实现方式。
循环检测
这种实现方式来自于Tangram,具体实现如下:
- baidu.string.getByteLength = function (source) {
- return String(source).replace(/[^\x00-\xff]/g, "ci").length;
- };
- /*
- * Tangram
- * Copyright 2009 Baidu Inc. All rights reserved.
- *
- * path: baidu/string/subByte.js
- * author: dron, erik
- * version: 1.1.0
- * date: 2009/11/30
- */
- /**
- * 对目标字符串按gbk编码截取字节长度
- *
- * @param {string} source 目标字符串
- * @param {number} length 需要截取的字节长度
- * @return {string} 字符串截取结果
- */
- baidu.string.subByte = function (source, length) {
- source = String(source);
- var getLen = baidu.string.getByteLength, i, len, current, next, currentLen, nextLen;
- if (length < 0 || getLen(source) <= length) {
- return source;
- }
- len = source.length;
- for (i = Math.floor(length / 2) - 1; i < len; i++) {
- current = next || source.substr(0, i);
- currentLen = nextLen || getLen(current);
- if (currentLen == length) {
- return current;
- }
- else {
- next = source.substr(0, i + 1);
- nextLen = getLen(next);
- if (nextLen > length) {
- return current;
- }
- }
- }
- return source;
- };
baidu.string是字符串常见操作的对象。
正则替换
这种方式的实现原理是先将中文替换成中文加个空格,这样变相的将一个中文变成了2个字节,然后在这个基础上截取,截取完成后在将中文加空格变成中文。
- baidu.string.subByte1 = function(source, length){
- return (source+'').substr(0,length).replace(/([^\x00-\xff])/g,'$1 ').substr(0,length).replace(/([^\x00-\xff]) /g,'$1');
- }
这种实现方式不管是从代码量上还是从效率上都要比第一种高很多,这里有个测试案例。