3

I have the following string:

  var str = 'd:\\projects\\my_project\\dist\\js\\example.js'

I want to split the string into an array as follows:

['d:', 'projects', 'my_project', 'dist', 'js', 'example', 'js']

How can do this with str.split(regex)? What is the proper regex I need?

Already tried str.split('(\.|\\)') and str.split('\.|\\') (i.e. w/out parenthesis)

Both '\.' and '\\' work when individually passed, but not combined.

Please help me regex masters!

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
mepley
  • 470
  • 4
  • 18

3 Answers3

3

You are passing string to to split() you need to pass RegExp().

Note: If you will use brackets like /(\.|\\)/) the result will also include . and \\

var str = 'd:\\projects\\my_project\\dist\\js\\example.js'
console.log(str.split(/\.|\\/))
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
2

Pass a regular expression to split:

var str = 'd:\\projects\\my_project\\dist\\js\\example.js';
const res = str.split(/\.|\\/);
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }

You were passing a string - it was looking for a literal pattern .|\ which it couldn't find. A regular expression (regex) uses slashes /, not quotes ' or ".

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
2

Other answers already explain that you need to pass a regular expression to String.split() instead of a string. So, alternatively, you can use this regular expression: /[\\.]/. This regular expression defines a Character Set:

var str = 'd:\\projects\\my_project\\dist\\js\\example.js';
console.log(str.split(/[\\.]/));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
Shidersz
  • 16,846
  • 2
  • 23
  • 48