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
.
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);
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With