How to extract values from a string in javascript?

16,609

Solution 1

Let's write a parser!

function parse(input)
{
    function parseSingle(input)
    {
        var parts = input.split('||'),
            part,
            record = {};

        for (var i=0; i<parts.length; i++)
        {
            part = parts[i].split('=');
            record[part[0]] = part[1];
        }

        return record;
    }

    var parts = input.split('++'),
        records = [];

    for (var i=0; i<parts.length; i++)
    {
        records.push(parseSingle(parts[i]));
    }

    return records;
}

Usage:

var string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2';

var parsed = parse(string);
/* parsed is:
[{id: "1", price: "500", name: "Item name", shipping: "0", quantity: "2"},
 {id: "2", price: "1500", name: "Some other name",  shipping: "10", quantity: "2"}]
*/

Solution 2

You can achieve this using regular expressions. For example, the regex /price=([0-9]+)/ will match price=XXX where XXX is one or more numbers. As this part of the regex is surrounded by parenthesis it explicitly captures the numeric part for you.

var string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2'

var priceRegex = /price=([0-9]+)/
var match = string.match(priceRegex);
console.log(match[1]); // writes 500 to the console log

Solution 3

First, split your string into two (or more) parts by ++ separator:

var strings = myString.split('++');

then for each of the strings you want an object, right? So you need to have an array and fill it like that:

var objects = [];

for (var i = 0; i < strings.length; ++i) {
    var properties = strings[i].split('||');
    var obj = {};
    for (var j = 0; j < properties.length; ++j) {
          var prop = properties[j].split('=');
          obj[prop[0]] = prop[1]; //here you add property to your object, no matter what its name is
    }
    objects.push(obj);
}

thus you have an array of all objects constructed from your string. Naturally, in real life I'd add some checks that strings indeed satisfy the format etc. But the idea is clear, I hope.

Solution 4

Try that:

var string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2';
var obj = new Array();
var arr = string.split('||');
for(var x=0; x<arr.length;x++){
    var temp = arr[x].split('=');
    obj[temp[0]] = temp[1]
}

alert(obj['id']); // alert 1

Solution 5

You're already using .split() to break down the string by || just take that a step further and split each of those sections by = and assign everything on the left the field and the right the value

Share:
16,609
Slavenko Miljic
Author by

Slavenko Miljic

Updated on June 05, 2022

Comments

  • Slavenko Miljic
    Slavenko Miljic about 2 years

    I need some help with extracting values from a cookie using javascript.

    The string in a cookie looks something like this:

    string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2'
    

    By using string.split() and string.replace() and a some ugly looking code I've somehow managed to get the values i need (price, name, shipping, quantity). But the problem is that sometimes not all of the strings in the cookie are the same. Sometimes the sting in a cookie will look something like this :

       string = 'id=c1||color=red||size=XL||price=500||name=Item name||shipping=0||quantity=2++id=c1||price=500||name=Item name||shipping=0||quantity=2'
    

    with some items having color and size as parameters and sometimes only one of those.

    Is there some more efficient way to explain to my computer that i want the part of the string after 'price=' to be a variable named 'price' etc.

    I hope I'm making sense I've tried to be as precise as I could.

    Anyway, thank you for any help

    EDIT: I just wanted to say thanks to all the great people of StackOverflow for such wonderfull ideas. Because of all of your great suggestions I'm going out to get drunk tonight. Thank you all :)