views:

294

answers:

2

I'm trying to parse a delimited string using the javascript split function. I'm using a double character delimiter. So for e.g. if the string contains employee related data with the following fields:

  1. Emp Id (mandatory)

  2. Name (mandatory)

  3. Age (optional)

  4. Mobile No (optional)

and the delimiter used is |* (i.e. pipe followed by star)

I may have data like this

5322|*Mike|*21|*077665543

5323|*Jen|*|*077665543

5324|*Raj|*25|*

5325|*Alan|*|*

How do I extract null values into the array returned by split?

If I use Record.split(/\|\*/) It seems to ignore the null values. Do I need to use other functions like regex exec + substring to do this? The split function seems to be quite convenient except for this issue.

+2  A: 

What you're doing is correct, and the null values are present.

>>> "5325|*Alan|*|*".split(/\|\*/)
["5325", "Alan", "", ""]
KennyTM
Indeed, if they weren't there they would return undefined: `"5325|*Alan|*|*".split(/\|\*/)[4]; // = undefined` - +1
Andy E
Thanks for the reply.I was using Internet Explorer and it did not return the null values. Tried the same code in Firefox and it did.
vivekraman
For the record, this is a bug (feature?) of Internet Explorer. NULL / empty strings are ignored in IE but picked up in Firefox. The code on this page provides a cross-browser implementation of split http://blog.stevenlevithan.com/archives/cross-browser-split
vivekraman
A: 

Do not confuse null with an empty string. Your regular expression splits the delimited string properly, capturing empty strings when the fields are "empty" as they should. If you need these array elements to be null, then you'd have to post-process the returned array yourself.

polygenelubricants