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!

0

3 Answers 3

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(/\.|\\/))

Sign up to request clarification or add additional context in comments.

Comments

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 ".

3 Comments

Thank you very much. I've tried to upvote, but not sure if you get credit because I have less than 15 reputation.
@mepley if you can't upvote you can always mark the most appropriate answer as "answered" by clicking the tick
@NickParsons Thank you! Okay almost to 15 reputation now lol
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;}

1 Comment

Thank you all for the help! Tried to upvote you all.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.