Help for splitting a string in JavaScript

I asked a question about line splitting as below:

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

and conclusion:

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

Kobe's answer:

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

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

Therefore, I cannot use the method .match().

How can i do this?

+3
source share
4 answers

Here is my hit:

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 RegExp:

/
 \s*   # Match Zero or more whitespace
 \|    # Match '|'
 \s+   # Match one or more whitespace (to avoid the ||)
/
+2
source

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

, :

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 leave d|=dintact.
\bmay introduce errors, although it may not be split if the channel is not between alphanumeric characters, for example, a=>(a+a)|b=>bit will not be split.

+1
source

I posted this in your other copy of this question (please do not ask the question several times!)

This should do it:

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

which gives:

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

All Articles