tokenize('100-(5.4 + 2/3)*5')
// [ '100', '-', '(', '5.4', '+', '2/3', ')', '*', '5' ]
Excuse me? What’s that hot mess inside the
split function? Let’s break it down step by step using a few examples of increasing complexity:
Pretty obvious: this splits the string
s anywhere it sees the minus sign symbol
The only difference from the previous example is the enclosing parens in the regex, which creates a capturing group. Here’s the key point of the entire article: If the regular expression contains capturing parentheses around the separator, then each time the separator is matched, the results of the capturing group are spliced into the output array.
This builds off the previous example by adding support for the addition symbol
\+. The backslash
\ is required to escape the regex. The vertical pipe
| acts as an OR statement (match
Hopefully, you now have all tools needed to understand
.split(/(-|\+|\/|\*|\(|\))/). Hope that made sense! Let me know in the comments if you liked this article, or ping me on twitter!