Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 487
bflemi3 Avatar asked Nov 23 '15 20:11

bflemi3


People also ask

Should I use forward slash or backslash?

The backslash is used only for computer coding. The forward slash, often simply referred to as a slash, is a punctuation mark used in English. The only time it is appropriate to use a comma after a slash is when demonstrating breaks between lines of poetry, songs, or plays.

How do you split a string in backslash?

split() method to split a string on the backslashes, e.g. my_list = my_str. split('\\') . The str. split method will split the string on each occurrence of a backslash and will return a list containing the results.

What does split \\ s do?

Splits this string around matches of the given regular expression. This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero.

How do I split a string with a specific symbol?

To split a string with specific character as delimiter in Java, call split() method on the string object, and pass the specific character as argument to the split() method. The method returns a String Array with the splits as elements in the array.


2 Answers

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

like image 70
CoderPi Avatar answered Oct 27 '22 01:10

CoderPi


This is what I ended up doing.

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

test.replace(/\\/g, '/').split('/');
like image 25
Stephen Paul Avatar answered Oct 27 '22 01:10

Stephen Paul