6

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

3 Answers 3

5

Use a Regexp negative lookahead:

  ";a;b;c;;e".split(/;(?!;)/)
Sign up to request clarification or add additional context in comments.

2 Comments

That is what you stated was your expected outcome.
See my answer, though. IE is actually wrong in dropping the first empty element.
1

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.

Comments

-1
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] );
}

Comments

Your Answer

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.