for loop string each word

javascript, jquery

Solution

If you mean you want to get that part of the string where it's length has reached 10, here's the answer:

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));

Live Demo

EDIT 1:

- Replaced `.match` with `.test`. The former returns a whole array while the latter simply returns true or false.

- Improved RegEx. Since we are checking only one character, no need for `^` and `+` that were before.

- Replaced `len` with `string.length`. Here's why.

Problem

if this type character `'這'` = `NonEnglish` each will take up 2 word space, and English will take up 1 word space, Max length limit is 10 word space; How to get the first 10 space. for below example how to get the result `This這 is`? I'm trying to use for loop from first word but I don't know how to get each word in string... ``` string = "This這 is是 English中文 …"; var NonEnglish = "[^\u0000-\u0080]+", Pattern = new RegExp(NonEnglish), MaxLength = 10, Ratio = 2; ```

Original source

Related problems