3

I'd asked a question about the splitting the a string like below:

Input string: a=>aa| b=>b||b | c=>cc

and the output:

a=>aa
b=>b||b 
c=>cc

Kobi's answer was:

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

His answer worked, but I need to use the .split() method and store the outputs in an array.

So I can't use the .match() Method.

How can I do it?

1
  • One question about the "output" - do you want ['a=>aa', 'b=>b||b', 'c=>cc'], or are you coming from a PHP background and thinking about a "hash table" (just an object in JS) {"a": "aa", "b": "b||b", "c":"cc"}? Commented Apr 30, 2010 at 9:00

4 Answers 4

2

Here's my stab:

var str = 'a=>aa| b=>b||b | c=>cc';
var arr = str.split(/\s*\|\s+/);
console.log(arr)
// ["a=>aa", "b=>b||b", "c=>cc"]

var obj = {}; // if we want the "object format"
for (var i=0; i<arr.length; i++) {
  str=arr[i];
  var match = str.match(/^(\w+)=>(.*)$/);

  if (match) { obj[match[1]] = match[2]; }
}
console.log(obj);

// Object { a:"aa", b:"b||b", c: "cc" }

And the RegExp:

/
 \s*   # Match Zero or more whitespace
 \|    # Match '|'
 \s+   # Match one or more whitespace (to avoid the ||)
/
Sign up to request clarification or add additional context in comments.

Comments

1

.match return array too, so there is no problem using .match

arr = "a=>aa|b=>b||b|c=>cc".match(/(?:[^|]|\|\|)+/g)
// a=>aa,b=>b||b,c=>cc
arr.length
// 3
arr[0]
// a=>aa

1 Comment

actually I need this question for my complier course. I explained the match function to my professor and he said that you must answer this question with split... One more thing: the input is : a=>aa|b=>b||b|c=>cc (there is no space between each character)
1

While I hate arguing with myself, another possible solution is:

var matches = 'a=>aa|b=>b||b|c=>cc'.split(/\b\s*\|\s*\b/g);

Meaning: split when you see | surrounded by spaces, and between alphanumeric characters.
This version will also leaves d|=d intact.
\b can introduce errors though, it might will not split if the pipe isn't between alphanumeric characters, for example a=>(a+a)|b=>b will not split.

Comments

0

I posted this in your other copy of this question (please don't ask a question multiple times!)

This ought to do it:

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

which yields:

["a=>aa", "b=>b||b", "c=>cc"]

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.