How can I split a string into an array using both "\\" or "/" as a separator (i.e. in a single regex) in Javascript?

Viewed 49

I'm attempting to split any arbitrary filepath such as:

"c:\\directory\\another_directory\\filename.ext" (Windows OS)

OR

"c:/directory/another_directory/filename.ext" (UNIX)

into an array, separated by either "\\" or "/" (depending on the operating system in which filepath strings are being read).

The desired output is an array such as:

['c:', 'directory', 'another_directory', 'filename.txt']

What is a regular expression I can use in a split method such as:

str.split(new RegExp(/(\\|/)/i)) (invalid regex)

Thanks in advance for your help.

1 Answers

Use .match, and match characters which are neither slashes nor backslashes:

const doSplit = str => str.match(/[^/\\]+/g);

console.log(doSplit(String.raw`c:\\directory\\another_directory\\filename.ext`));
console.log(doSplit("c:/directory/another_directory/filename.ext"));

Related