Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to do split() in javascript and ignore blank entries?

I have the following C# code that i need to convert to javascript:

    static private string[] ParseSemicolon(string fullString)
    {
        if (String.IsNullOrEmpty(fullString))
            return new string[] { };

        if (fullString.IndexOf(';') > -1)
        {
            return fullString.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(str => str.Trim()).ToArray();
        }
        else
        {
            return new[] { fullString.Trim() };
        }
    }

i see that javascript has a split() function as well but i wanted to see if there is built in support for the other checks or i have to do an additional loop around the array afterwards to "clean up" the data?

like image 636
leora Avatar asked Mar 17 '14 11:03

leora


4 Answers

You can use filter, but this function is implemented only in more recent browsers.

"dog;in;bin;;cats".split(";").filter(function (x) { return x != ""; });
like image 162
Matthew Mcveigh Avatar answered Sep 30 '22 19:09

Matthew Mcveigh


You can use a RegExp with a quantifier to split on any consecutive count of the delimiter:

var parts = input.split(/;+/);

Such as:

var input = "foo;;;bar;;;;;;;;;baz";
var parts = input.split(/;+/);

console.log(parts);
// [ "foo", "bar", "baz" ]
like image 20
Jonathan Lonowski Avatar answered Sep 30 '22 18:09

Jonathan Lonowski


Try this

"hello;aamir;;afridi".split(';').filter(Boolean)

or

"hello;;aamir;;;;afridi".split(';').filter(Boolean)

results in

["hello", "aamir", "afridi"]

And to convert it back to string, use this

"hello;aamir;;afridi".split(';').filter(Boolean).join(' ')

or

"hello;aamir;;afridi".split(';').filter(Boolean).join(';')
like image 30
Aamir Afridi Avatar answered Sep 30 '22 19:09

Aamir Afridi


Unfortunately javascript split() does not check for doublespaces etc, you would need to clean up your array later

var str = "How;are;;you;my;;friend?";
var arr = str.split(";");

alert(arr);

http://jsfiddle.net/p58qm/2/

You can then update the array with this loop

len = arr.length, i;

for(i = 0; i < len; i++ )
arr[i] && arr.push(arr[i]);  // copy non-empty values to the end of the array

arr.splice(0 , len);

alert(arr);

http://jsfiddle.net/p58qm/3/

like image 24
Foxhoundn Avatar answered Sep 30 '22 19:09

Foxhoundn