6

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.

Sergino
  • 10,128
  • 30
  • 98
  • 159

3 Answers3

19

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);
Louay Alakkad
  • 7,132
  • 2
  • 22
  • 45
  • 4
    If you want to do this way, then use `value.split('/').filter(Boolean);` – Tushar Dec 19 '15 at 13:11
  • I'd typically use ES6 to make it look prettier, but yeah that's also possible. – Louay Alakkad Dec 19 '15 at 13:12
  • 1
    For reference of how `Boolean` passed to `filter` works. [What is the `filter` call for in this string split operation?](http://stackoverflow.com/a/33516569/2025923) and [Get number of non-empty elements from nested arrays](http://stackoverflow.com/a/33802897/2025923) – Tushar Dec 19 '15 at 13:23
8

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>');
Tushar
  • 85,780
  • 21
  • 159
  • 179
  • what does two last params `...0, 4` means in `JSON.stringify()` ? – Sergino Dec 19 '15 at 13:22
  • @sreginogemoh Those are just for showing results on the page, the parameters are for formatting purpose. You can only use `str.match(/[^\/]+/g);` code to get matches. – Tushar Dec 19 '15 at 13:24
0

If you still want to use String to match a symbol you can try using: RegExp("/", "g") - but this is not the best case, if you still want not to match escaped symbol \ and provide some API for use you can user RegExp("[^\/]*", "g") or /[^\/]*/g