for循环字符串每个单词

use*_*888 8 javascript jquery

如果这个类型字符'?'= 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)

Hig*_*ots 8

如果你的意思是你希望得到字符串中长度达到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:

  1. 替换.match为.test.前者返回整个数组,而后者只返回true或false.
  2. 改进的RegEx.因为我们只检查一个字符,所以不需要^和+以前一样.
  3. 替换len为string.length.这就是原因.

  • 请注意,因为你在"字符串的每个字符"上使用正则表达式需要很长时间才能处理 (2认同)