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(/(/)/)

A K
  • 1,464
  • 2
  • 12
  • 18
  • Possible duplicate of [JS string.split() without removing the delimiters](https://stackoverflow.com/questions/4514144/js-string-split-without-removing-the-delimiters) – Anderson Green Apr 26 '18 at 00:39

2 Answers2

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.

Web_Designer
  • 72,308
  • 93
  • 206
  • 262
ConnorsFan
  • 70,558
  • 13
  • 122
  • 146
-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));
John
  • 760
  • 5
  • 12