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

javascript - Split string on backslash or forward slash - Stack Overflow

programmeradmin1浏览0评论

Given the following test cases:

  1. res/js/test
  2. res\js\test
  3. res/js\test
  4. res\js/test

How can I split a string by either forward slash or backslash? My attempt works when the string is only backslashes(test case 1) but doesn't work for forward slashes or a mixture of both (test cases 2, 3, 4).

test.split(/[\\\/]/);

Here's my fiddled attempt

Given the following test cases:

  1. res/js/test
  2. res\js\test
  3. res/js\test
  4. res\js/test

How can I split a string by either forward slash or backslash? My attempt works when the string is only backslashes(test case 1) but doesn't work for forward slashes or a mixture of both (test cases 2, 3, 4).

test.split(/[\\\/]/);

Here's my fiddled attempt

Share Improve this question asked Nov 23, 2015 at 20:00 bflemi3bflemi3 6,79021 gold badges95 silver badges158 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 10

Your string does not contain any backslashes, but esaped \j, and \t wich is the value for tab. Your Code is correct, but your input is not, use this:

var test = [
    'res/js/test',
    'res\\js\\test',
    'res/js\\test',
    'res\\js/test'
    ];

Only a escaped backslash will make a backslash in a string '\\'

This is what I ended up doing.

I replaced all backslashes with forward slashes before splitting by forward slash.

test.replace(/\\/g, '/').split('/');
发布评论

评论列表(0)

  1. 暂无评论