2

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?

Mateen Ulhaq
27.9k21 gold badges122 silver badges155 bronze badges
asked Aug 18, 2011 at 2:23

4 Answers 4

1

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.
answered Aug 18, 2011 at 2:29
Sign up to request clarification or add additional context in comments.

2 Comments

I think the w_temp[1] is an error. From the question, I think w_temp is the string "XXX CHAN Tai-Man"
@Phil: The question notes that w_name[0] returns the correct value, so w_temp[1] must be correct.
0

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.

answered Aug 18, 2011 at 2:29

Comments

0

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);
}
answered Aug 18, 2011 at 2:34

Comments

0

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];
}
answered Aug 18, 2011 at 2:33

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.