Hey everyone! I'm trying to manipulate a string in JavaScript where I want to enclose all the words that are separated by 'OR' in parentheses. For example, I have the string: 'w1 w2 OR w3 OR w4 w5 w6 OR w7', and I want to transform it to 'w1 ( w2 OR w3 OR w4 ) w5 ( w6 OR w7 )'. Any tips or regex patterns that could help me out? Thanks in advance!
2 Answers
You might want to check out regex101.com! It's a great tool for testing and debugging your regex patterns, which could be super helpful for your problem. Good luck!
While regex can do a lot, this might not be the best approach. Instead of using regex, consider splitting your string by spaces and iterating over the tokens. You can create a new string that checks each substring and adds parentheses whenever needed. It's often clearer and more efficient!

Thanks for the suggestion! I actually ended up doing something similar. I wrote a function that checks for 'OR' and handles the grouping pretty well. I shared my approach if you want to check it out!