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.

1
  • yeah it is just my wrong formatting here Commented Dec 19, 2015 at 13:30

4 Answers 4

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);
Sign up to request clarification or add additional context in comments.

3 Comments

If you want to do this way, then use value.split('/').filter(Boolean);
I'd typically use ES6 to make it look prettier, but yeah that's also possible.
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>');

2 Comments

what does two last params ...0, 4 means in JSON.stringify() ?
@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.
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

Comments

0

category one liner, no regx , no empty string :

    const multiSplit = (toSplit, delimitersArray) => delimitersArray.reduce((all, s) => all.map(v => v.split(s).filter(Boolean)).flat() ,[toSplit])

    console.log(multiSplit('what is going on with the world ??? u sure u want to leave it all to ai ?!', ['?',' ', '\n']))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.