Split the string in Javascript, but keep the / separator

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

I had a problem splitting this line. Can I get help on this?

String.split (/ (/) /)

+2
javascript split
Apr 7 '16 at 1:06 on
source share
2 answers

You can do this with a regex using ''.match() instead of split :

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

The first part [^\/]+\/? matches the number of unbound slashes that it may optionally follow / . The second part \/ (after or: | ) matches a single slash.

+4
Apr 7 '16 at 1:29
source share

If you want to split it, you must add "/"
after that. But a more efficient way would be regular expression .

Divide and add "/" subsequently:

 var string = 'Animation/rawr/javascript.js'; var arr = string.split("/"); arr.forEach(function(e, i, a) { a[--i] += "/"; }); document.write(JSON.stringify(arr)); 
0
Apr 7 '16 at 1:33
source share



All Articles