Joe Yan
Joe Yan

Reputation: 2095

Javascript split array

I have a JavaScript array which contain the staff's Chinese and English names.

Example:

XXX MA Yo-Yo

Where XXX represents the Chinese name: 馬友友.

I want to split this into two parts by using the 1st space " " as an indicator.

for (i = 0; i < /* ... */)
{
    w_temp = arr[i];
    w_name = w_temp[1].split(' ', 1);

    /* ... */
}

w_name[0] successfully returns 馬友友. But w_name[1] returns undefined, which cannot return MA Yo-Yo.

How can I split it into two parts?

Upvotes: 2

Views: 5047

Answers (4)

Phil
Phil

Reputation: 164795

Try this

for (var i = 0; i < arr.length; i++) {
    var w_temp = arr[i];

    // assuming w_temp contains an array where the second item
    // is the full name string
    var parts = w_temp[1].match(/^(.+?) (.+)$/);
    var cn_name = parts[1];
    var en_name = parts[2];
}

Upvotes: 0

Tu Tran
Tu Tran

Reputation: 1977

Because you invoke split method with limit = 1, then w_name has only 1 item.

In addition, yours input string has 2 whitespace, therefore, if you use split without limit parameter, w_name will contains 3 items ('XXX', 'CHAN', and 'Tai-Man').

I think you should use this:

var idx = str.indexOf(' ');
if (idx != -1) {
    var cn_name = str.substring(0, idx);
    var en_name = str.substring(idx + 1);
}

Upvotes: 0

icktoofay
icktoofay

Reputation: 129011

Replace your existing w_name = ... line with something like this:

w_name = w_temp[1].split(' ');
w_name = [w_name[0], w_name.slice(1).join(' ')];

The ,1 you had earlier meant to stop parsing as soon as it came to the first space. This is not what you want; you want the part before the first space as one item and the part after as another. The new code parses all of the elements. After that, it sets it to an array consisting of:

  1. The already-existing first element, and
  2. The parts after the first element re-joined.

Upvotes: 1

Stephen
Stephen

Reputation: 3432

You have

 split(' ', 1)

The 1 means to return at most one part. You should just ommit that or change it to two if thats what you need.

Upvotes: 0

Related Questions