新版(物件導向版)
const strSplit={
regSplit: /(?<=\S)(?=[\u4E00-\u9FFF])|(?<=[\u4E00-\u9FFF])(?=\S)|(?<=\s)(?=\S)|(?<=\S)(?=\s)/g,
regChinese: /[\u4E00-\u9FFF]/,
strLen: 28,
addLen: 0,
Arr_i: 0,
arrStr: [],
in: function(p_str)
{
this.addLen = 0;
this.Arr_i = 0;
this.arrStr = [''];
let strSpiltArr = p_str.split(this.regSplit);
strSpiltArr.forEach((l_str) => {
if(this.regChinese.test(l_str))
{
this.strSpilt(l_str,2);
}
else
{
this.strSpilt(l_str,l_str.length);
}
});
},
strSpilt: function(p_str,p_len)
{
this.addLen += p_len;
if( this.addLen > this.strLen)
{
this.Arr_i++;
this.arrStr[this.Arr_i] = "";
this.addLen = p_len;
}
this.arrStr[this.Arr_i] += p_str;
}
};
strSplit.in("您的下載速度有多快?只需幾秒,FAST.com 的簡易網路速度測試就可以估計您的網路服務商速度。");
strSplit.arrStr
$(".spiltTag").each(function(){
const tagId = $(this).attr('id');
const tagVal = $(this).val();
strSplit.in(tagVal);
for(let i=0;i<strSplit.arrStr.length;i++)
{
alert(strSplit.arrStr[i]);
let l_tagId = `#${tagId}${i}`;
$(l_tagId).val(strSplit.arrStr[i]);
}
});
舊版
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script>
const arr1 = [];
const arr2 = [];
function aa(strVal , strMaxLenb)
{
let g_strType = "";
const rex = /[\u4E00-\u9FFF]/;//抓出中文字
for (const char of strVal)
{
let l_strType = "";
if( char == " " )
{
arr1.push(char);
l_strType = " ";
}
else
{
let l_lenb = 1;
if( rex.test(char) )
{
l_strType="C";
l_lenb = 2;
}
else
{
let l_strType = "E";
}
if( g_strType != l_strType )
{
arr1.push(char);
}
else
{
var tmpVal = arr1.slice(-1) + char;
if( tmpVal.length*l_lenb > strMaxLenb )
{
arr1.push(char);
}
else
{
if(arr1.length == 0) arr1.push("");
const lastElement = arr1.pop(); //pop就是刪除並取出值!!!
arr1.push(lastElement + char);
}
}
}
g_strType = l_strType;
}
arr2.push("");
arr1.forEach((l_strVal) => {
const lastVal = arr2.slice(-1) + l_strVal;
const newVal = lastVal.replace(/[\u4E00-\u9FFF]/g, " ");
if( newVal.length > strMaxLenb )
{
arr2.push(l_strVal);
}
else
{
const lastElement = arr2.pop();
arr2.push(lastElement + l_strVal);
}
});
}
</script>
</head>
<body onload="aa('您的下載速度有多快?只需幾秒,FAST.com 的簡易網路速度測試就可以估計您的網路服務商速度。', 20)">
<DIV ID="D1"></DIV>
</body>
</html>