2

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:

split(/ \ | /)

or

split(/ \| (?! \ |) /)

but didn't work.

please help me...

I really need it fast.

3 Answers 3

3

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

"a=>aa| b=>b||b | c=>cc".split(/\|(?=\s)/)
# a=>aa
# b=>b||b 
# c=>cc
Sign up to request clarification or add additional context in comments.

1 Comment

Note: my answer only works for OP's example. please take a look Kobi's answer, thats more appropriate one actually.
1

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].

1 Comment

Thanks. That depends on the context though, if the OP has tokens with single pipes (which is very possible), your version will work better.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.