I am looking to split a string by several separators, but I would like to include the separators in the returned array. For example I want to split this string "hello i=5 (goodbye)" by spaces, assignment operators, and parenthesis. The only way I know how to split that string is by doing something like this: "hello i=5 (goodbye)".split(/[\s=)(]/); but the returned array is ["hello", "i", "5", "", "goodbye", ""]. Is there a way to include the separators in the result? I would like it to return ["hello", "i", "=", "5", "(", "goodbye", ")"]
Thanks for the help!
You can use
matchand match for the symbols you want and groups that don’t match the symbols you want in a single regexp:If you want to get rid of the spaces you can chain
.filter(function(el){ return el.trim(); })to the above.