Robert
Robert

Reputation: 816

Regex to retrieve two variables between brackets

Im trying to retrieve two variables between two double brackets. So far I have this:

var regex = /\[\[\s([a-z]+):*\s*([\d])*\s\]\]/g;
var obj = {};
var text = '[[ dogs: 1 ]] [[ dogs: 2 ]] [[ cats: 1 ]]';
var module = text.replace(regex, function (match, key, value) {
    obj[key] = value;
    console.log(obj);
});

The outcome is:

Object {dogs: "2", cats: "1"}

What I want is:

Object {dogs: "1", dogs: "2", cats: "1"}

For the life of me I cannot figure out why dogs only shows the 2nd id.

Upvotes: 2

Views: 127

Answers (3)

Renato Gama
Renato Gama

Reputation: 16519

Since you cant have multiple properties with the same name my suggestion is that you use an array to store different values, like this;

http://jsbin.com/qiqacifata/1/edit?js,console

var regex = /\[\[\s([a-z]+):*\s*([\d])*\s\]\]/g;
var obj = {};
var text = '[[ dogs: 1 ]] [[ dogs: 2 ]] [[ cats: 1 ]]';
var module = text.replace(regex, function (match, key, value) {
    if(!obj[key]) {
        obj[key] = [];
    }
    obj[key].push(value);

});

console.log(obj);

Results in;

{
  cats: ["1"],
  dogs: ["1", "2"]
}

Upvotes: 2

Ivan Drinchev
Ivan Drinchev

Reputation: 19581

Your bug is not inside the regex is inside the object.

You can't have an object with two identical keys.

I suggest you put your data into array and iterate when you need it :

var regex = /\[\[\s([a-z]+):*\s*([\d])*\s\]\]/g;
var arr = [];
var text = '[[ dogs: 1 ]] [[ dogs: 2 ]] [[ cats: 1 ]]';
var module = text.replace(regex, function (match, key, value) {
    var obj = {}
    obj[key] = value;
    arr.push(obj);
});
console.log(arr); // [{dogs:1},{dogs:2},{cats:1}]

Upvotes: 4

Scimonster
Scimonster

Reputation: 33409

It's because objects cannot contain multiple items with the same key. When you set dogs the second time, it overwrites the first instance.

Some alternate solutions include creating an array of objects:

var regex = /\[\[\s([a-z]+):*\s*([\d])*\s\]\]/g;
var arr = [];
var text = '[[ dogs: 1 ]] [[ dogs: 2 ]] [[ cats: 1 ]]';
var module = text.replace(regex, function (match, key, value) {
    var obj = {};
    obj[key] = value;
    arr.push(obj);
    console.log(arr);
});

Or using creating an object of arrays:

var regex = /\[\[\s([a-z]+):*\s*([\d])*\s\]\]/g;
var obj = {};
var text = '[[ dogs: 1 ]] [[ dogs: 2 ]] [[ cats: 1 ]]';
var module = text.replace(regex, function (match, key, value) {
    if (obj[key]) {
        obj[key].push(value);
    } else {
        obj[key] = [value];
    }
    console.log(obj);
});

Upvotes: 5

Related Questions