javascriptregexsplit

Split string on backslash or forward slash


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


Solution

  • 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 '\\'