I am not good at regex, thats why I ask here.
Suppose I have the following strings:
let a = 'A,B,C,D',
b = 'A,B|C,D',
c = 'A|B|C|D'
I'd like to split them using a comma ,, and a pipe |. Something like:
// a.split(regex)
Or similar while considering the performance.
All the above strings should result in // [A, B, C, D]
How would I write a regex for that. Also, a reference to teach myself regex would be welcome.
Try RegEx /[,|]/
By placing part of a regular expression inside round brackets, you can group that part of the regular expression together.
Here ,| matches a single character in the list.
let a = 'A,B,C,D',
b = 'A,B|C,D',
c = 'A|B|C|D'
a = a.split(/[,|]/);
b = b.split(/[,|]/);
c = c.split(/[,|]/);
console.log(a);
console.log(b);
console.log(c);
You can try this:
str.split(/[|,]+/)
Here, regex specifies that | and , can occur 1 or more times and if found it will split function will do the job.
This is the best tool when it comes to testing regex: https://regex101.com/
I learned my regex here: https://regexr.com/
Hope this helps!
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