Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 340
vikmalhotra Avatar asked Dec 14 '10 09:12

vikmalhotra


2 Answers

Use a Regexp negative lookahead:

  ";a;b;c;;e".split(/;(?!;)/)
like image 54
Brian Rose Avatar answered Sep 24 '22 06:09

Brian Rose


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.

like image 40
Matthew Flaschen Avatar answered Sep 24 '22 06:09

Matthew Flaschen