-1

I have ab array something like this :

const operators = ['<','>','>=','<>','=']

and a string something like this :

const myStr = 'Some Operand > Some Other Operand'

as you see in this string I have > character that exists in operator array now I want to split string base on operators characters that exisits in array. I know I can do this with regex but i can't figure how to do it

MBehtemam
  • 7,865
  • 15
  • 66
  • 108
  • @T.J.Crowder I update my question but that's just for knowing is split or anyone do this before. – MBehtemam Jul 21 '18 at 12:01
  • 1
    Without regex: `operators.reduce((sum, op) => [].concat(...sum.map((str) => str.split(op))), [myStr])` – James Jul 21 '18 at 12:34

1 Answers1

2

You can define alternation in regex with the vertical bar: (<|>|>=|<>|=), this will match one of the specified patterns (your operators).

And you can pass a regex to the split() function:

function f(s) { return s.split(/(<>|>=|>|<|=)/); }
console.log(f("Some Operand > Some Other Operand"));
console.log(f("Some Operand >= Some Other Operand"));

Edit: inside the regex above, I wrote the 2-character operators first, then the single-character ones. This way, it will match all operators correctly. You can even simplify the regex by using optionals:

function f(s) { return s.split(/(<>?|>=?|=)/); }
console.log(f("Some Operand > Some Other Operand"));
console.log(f("Some Operand >= Some Other Operand"));

If you're interested in doing this without regex, you can check out this answer which uses split and join functions.

juzraai
  • 5,693
  • 8
  • 33
  • 47
  • *"Note that I have added space around the operator pattern, so you don't need to trim the operands."* Two issues: 1. It's fairly unusual to **require** spaces around operators, and 2. This doesn't mean OP doesn't have to trim, because it doesn't handle multiple spaces. – T.J. Crowder Jul 21 '18 at 12:11
  • You're absolutely right, thanks. Since the original post doesn't mention spaces/trimming, I'll remove it from my answer too. – juzraai Jul 21 '18 at 12:14
  • @juzraai after removing space if string contain `>=` it splits with `>` how do I exactly if string contains `>=` with `>=` and not `>` – MBehtemam Jul 22 '18 at 03:48
  • Oh I see. Please see my edited answer. I changed the order of the operators inside the regex. Also I provided a simplified pattern. – juzraai Jul 22 '18 at 09:00