最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to split string without getting empty values to the output array - Stack Overflow

programmeradmin3浏览0评论

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.

Share Improve this question edited Dec 19, 2015 at 13:31 Sergino asked Dec 19, 2015 at 13:09 SerginoSergino 10.8k37 gold badges107 silver badges181 bronze badges 1
  • yeah it is just my wrong formatting here – Sergino Commented Dec 19, 2015 at 13:30
Add a comment  | 

3 Answers 3

Reset to default 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);

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

发布评论

评论列表(0)

  1. 暂无评论