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
.
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
.
- yeah it is just my wrong formatting here – Sergino Commented Dec 19, 2015 at 13:30
3 Answers
Reset to default 19Try 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);
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>');
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