Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help for splitting a string in JavaScript

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?

like image 841
Hero Avatar asked Apr 06 '26 10:04

Hero


2 Answers

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 ||)
/
like image 121
gnarf Avatar answered Apr 09 '26 00:04

gnarf


.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
like image 33
YOU Avatar answered Apr 08 '26 22:04

YOU



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!