如果这个类型字符'?'= NonEnglish每个将占用2个字空间,而英语将占用1个字空间,最大长度限制为10个字空间; 如何获得前10个空间.
以下示例如何获得结果This? is?
我试图从第一个单词开始使用for循环,但我不知道如何在字符串中获取每个单词...
string = "This? is? English?? …";
var NonEnglish = "[^\u0000-\u0080]+",
Pattern = new RegExp(NonEnglish),
MaxLength = 10,
Ratio = 2;
Run Code Online (Sandbox Code Playgroud)
如果你的意思是你希望得到字符串中长度达到10的部分,这就是答案:
var string = "This? is? English?? …";
function check(string){
// Length of A-Za-z characters is 1, and other characters which OP wants is 2
var length = i = 0, len = string.length;
// you can iterate over strings just as like arrays
for(;i < len; i++){
// if the character is what the OP wants, add 2, else 1
length += /\u0000-\u0080/.test(string[i]) ? 2 : 1;
// if length is >= 10, come out of loop
if(length >= 10) break;
}
// return string from the first letter till the index where we aborted the for loop
return string.substr(0, i);
}
alert(check(string));
Run Code Online (Sandbox Code Playgroud)
编辑1:
.match为.test.前者返回整个数组,而后者只返回true或false.^和+以前一样.len为string.length.这就是原因.| 归档时间: |
|
| 查看次数: |
1604 次 |
| 最近记录: |