Skip to content Skip to sidebar Skip to footer

Write An Expression In Javascript

I need a javascript code that split a string like below: Input string: 'a=>aa| b=>b||b | c=>cc' Output: a=>aa b=>b||b c=>cc I'd written different codes like:

Solution 1:

Split with /\|(?=\s)/ for your case

"a=>aa| b=>b||b | c=>cc".split(/\|(?=\s)/)
# a=>aa
# b=>b||b 
# c=>cc

Solution 2:

This confusing looking regex will work without spaces around the pipes:

var matches = "a=>aa|b=>b||b|c=>cc".match(/(?:[^|]|\|\|)+/g)

Instead of splitting, it searches for tokens with double pipes, but not single. If you have spaces and need to match b=>b|b | c=>5 use S.Mark's regex, but this can help in other cases.
To clarify, [^|]|\|\| reads [not a pipe] OR [two pipes].


Solution 3:

I tested the first answer and it did not work as I believe you intended:

"a=>aa| b=>b||b | c=>cc".split( "\| ");

unfortunately the answer that I came up with isn't much better just add a space after the pipe marker in your regex. Also answer by @S.Mark is valid, tested.


Post a Comment for "Write An Expression In Javascript"