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?
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 ||)
/
.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With