Given the following test cases:
res/js/test
res\js\test
res/js\test
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
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.
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.
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.
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.
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('/');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With