如何从JavaScript中的字符串中提取值? [英] How to extract values from a string in javascript?

查看:505
本文介绍了如何从JavaScript中的字符串中提取值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用javascript从cookie中提取值时,我需要一些帮助.

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

cookie中的字符串如下所示:

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'

通过使用string.split()和string.replace()以及一些难看的代码,我设法以某种方式设法获得了我需要的值(价格,名称,运输,数量).但是问题在于,有时cookie中的并非所有字符串都是相同的.有时,cookie中的刺痛看起来像这样:

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.

是否有一些更有效的方式向我的计算机解释我希望'price ='之后的字符串部分是一个名为'price'的变量,等等.

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

我只想对StackOverflow的所有优秀人士的如此精彩的想法表示感谢.由于您的所有建议,我今晚要喝醉了.谢谢大家:)

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

推荐答案

让我们编写一个解析器!

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"}]
*/

这篇关于如何从JavaScript中的字符串中提取值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆