Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split string without getting empty values to the output array

I am using split function to split my string /value/1

var value = "/value/1/";

var arr = value.split("/");

in result I will get an array with 4 elements "", "value", "1", ""; But I really need the nonempty values in the output array. Is there any way to produce an array base on my input string but array without blank elements?

My string could be /value/1/ /value/1 /value/ /value basically I am precessing http request.url.

like image 411
sreginogemoh Avatar asked Dec 19 '15 13:12

sreginogemoh


2 Answers

Try using Array#filter.

var arr = value.split("/").filter(function (part) { return !!part; });

Or the same shorter version as Tushar suggested.

var arr = value.split("/").filter(Boolean);
like image 93
Louay Alakkad Avatar answered Nov 01 '22 15:11

Louay Alakkad


You can use match with regex.

str.match(/[^\/]+/g);

The regex [^\/]+ will match any character that is not forward slash.

function getValues(str) {
  return str.match(/[^\/]+/g);
}

document.write('<pre>');
document.write('<b>/value/1/</b><br />' + JSON.stringify(getValues('/value/1/'), 0, 4));
document.write('<br /><br /><b>/value/1</b><br />' + JSON.stringify(getValues('/value/1'), 0, 4));
document.write('<br /><br /><b>/value/</b><br />' + JSON.stringify(getValues('/value/'), 0, 4));
document.write('<br /><br /><b>/value</b><br />' + JSON.stringify(getValues('/value'), 0, 4));
document.write('</pre>');
like image 20
Tushar Avatar answered Nov 01 '22 16:11

Tushar