4
var string = 'Animation/rawr/javascript.js'

//expected output 
// ['Animation/', 'rawr/', 'javascript.js']

I'm having trouble splitting this string properly. Can I get some help on this?

string.split(/(/)/)

1

2 Answers 2

9

You can do it with a regular expression using ''.match() instead of split:

var str = 'Animation/rawr/javascript.js';
var tokens = str.match(/[^\/]+\/?|\//g);

The first part [^\/]+\/? matches as many non forward slashes it can optionally followed by a /. The second part \/ (after the or: |) matches a lone forward slash.

Sign up to request clarification or add additional context in comments.

Comments

-1

If you want to split it, you have to add the "/"
afterwards. But the more efficient way would be a regex.

Split and add "/" afterwards:

var string = 'Animation/rawr/javascript.js';
var arr = string.split("/");

arr.forEach(function(e, i, a) {
  a[--i] += "/";
});

document.write(JSON.stringify(arr));

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.