What is the best way to do split () in javascript and ignore empty 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, but I wanted to see if there is built-in support for other checks, or do I need to do an extra loop around the array after that to β€œclear” the data?

+7
javascript jquery string split c #
source share
6 answers

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

 "dog;in;bin;;cats".split(";").filter(function (x) { return x != ""; }); 
+7
source share

You can use RegExp with a quantifier to split into any sequential separator counter:

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

For example:

 var input = "foo;;;bar;;;;;;;;;baz"; var parts = input.split(/;+/); console.log(parts); // [ "foo", "bar", "baz" ] 
+7
source share

try it

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

or

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

leads to

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

And to convert it to string use this

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

or

 "hello;aamir;;afridi".split(';').filter(Boolean).join(';') 
+4
source share

Split also requires handling empty results. However when another way

http://jsfiddle.net/9mHug/1/

 var str = "aaa,bbb;ccc ddd , eee"; var sp = str.match(/\w+/g); alert(sp); 

This will give you a clean array of words only. \w is a regular expression search that finds all letters of a particular type [a-zA-Z0-9_]

+1
source share

Unfortunately, javascript split () does not check for two-local spaces, etc., you will need to clear your array later

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

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

Then you can 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/

+1
source share

Try the following:

 function parseSemicolon(fullString) { var result = new Array(); if (!!fullString && fullString.length > 0) { fullString = fullString.trim(); if (fullString.indexOf(';') > -1) { result = fullString.split(';'); for (var i = 0; i < result.length; i++) { result[i] = result[i].trim(); } } else { result = new Array(fullString); } } return result; } 

This should have the same effect as your C # script.

+1
source share

All Articles