简体   繁体   中英

Split String in Javascript but keep delimiter /

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

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.

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)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM