最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Split String in Javascript but keep delimiter- Stack Overflow

programmeradmin1浏览0评论
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(/(/)/)

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

Share asked Apr 7, 2016 at 1:06 A KA K 1,6742 gold badges13 silver badges18 bronze badges 1
  • Possible duplicate of JS string.split() without removing the delimiters – Anderson Green Commented Apr 26, 2018 at 0:39
Add a ment  | 

2 Answers 2

Reset to default 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.

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

发布评论

评论列表(0)

  1. 暂无评论