vikmalhotra
vikmalhotra

Reputation: 10071

split a string using javascript

I have a string like ";a;b;c;;e". Notice that there is an extra semicolon before e. I want the string to be split in a, b, c;, e. But it gets split like a, b, c, ;e.

My code is

var new_arr = str.split(';');

What can I do over here to get the result I want?

Regards

Upvotes: 6

Views: 804

Answers (3)

pooja
pooja

Reputation: 2412

var myArr = new Array();

var myString = new String();

myString = ";a;b;c;;e";

myArr = myString.split(";");


for(var i=0;i<myArr.length;i++)
{
    document.write( myArr[i] );
}

Upvotes: -1

Matthew Flaschen
Matthew Flaschen

Reputation: 284786

Interesting, I get ["", "a", "b", "c", "", "e"] with your code.

var new_array = ";a;b;c;;e".split(/;(?!;)/);
new_array.shift();

This works in Firefox, but I think it's correct. You might need this cross-browser split for other browsers.

Upvotes: 1

Brian Rose
Brian Rose

Reputation: 1725

Use a Regexp negative lookahead:

  ";a;b;c;;e".split(/;(?!;)/)

Upvotes: 5

Related Questions