How to Enclose Words Joined by ‘OR’ in JavaScript?

0
7
Asked By CodeCrafter82 On

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

Answered By RegexNinja99 On

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!

Answered By HelpfulHacker24 On

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!

CodeCrafter82 -

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!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.