简体   繁体   English

如何从javascript中的字符串中提取值?

[英]How to extract values from a string in javascript?

I need some help with extracting values from a cookie using javascript.我需要一些帮助来使用 javascript 从 cookie 中提取值。

The string in a cookie looks something like this: cookie 中的字符串如下所示:

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).通过使用 string.split() 和 string.replace() 以及一些难看的代码,我以某种方式设法获得了我需要的值(价格、名称、运输、数量)。 But the problem is that sometimes not all of the strings in the cookie are the same.但问题是有时并非 cookie 中的所有字符串都相同。 Sometimes the sting in a cookie will look something like this :有时 cookie 中的刺会是这样的:

   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.是否有一些更有效的方法可以向我的计算机解释我希望 'price=' 之后的字符串部分是一个名为 'price' 等的变量。

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.编辑:我只是想感谢 StackOverflow 的所有伟大的人提供了如此美妙的想法。 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"}]
*/

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.例如,正则表达式/price=([0-9]+)/将匹配price=XXX ,其中 XXX 是一个或多个数字。 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

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

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.自然,在现实生活中,我会添加一些检查字符串确实满足格式等。但我希望这个想法很清楚。

If you can replace the ||如果可以替换|| with & , you could try to parse it as if it were a query string .使用& ,您可以尝试将其解析为查询字符串 A personal note - JSON-formatted data would've been easier to work with.个人笔记 - JSON 格式的数据会更容易使用。

I would attach the data to a javascript object.我会将数据附加到一个 javascript 对象。

  var settingsObj = {};
  var components = thatString.split('||');

  for(var j = 0; j < components.length; j++)
  {
       var keyValue = components[j].split('=');

       settingsObj[keyValue[0]] = keyValue[1];
  }

  // Now the key value pairs have been set, you can simply request them

  var id = settingsObj.id; // 1 or c1
  var name = settingsObj.name; // Item Name, etc

You're already using .split() to break down the string by ||您已经在使用 .split() 按 || 分解字符串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更进一步,将每个部分按 = 拆分,然后将左侧的所有内容分配给字段,将右侧的所有内容分配给值

This should get the first match in the string:这应该得到字符串中的第一个匹配项:

string.match(/price=(\d{1,})/)[1]

Note this will only match the first price= in the string, not the second one.请注意,这只会匹配字符串中的第一个 price=,而不匹配第二个。

If you can use jQuery, it wraps working with cookies and lets you access them like:如果您可以使用 jQuery,它会与 cookie 一起工作,并让您像这样访问它们:

Reading a cookie: var comments = $.cookie('comments');读取 cookie: var comments = $.cookie('comments');

Writing a cookie: $.cookie('comments', 'expanded');写一个 cookie: $.cookie('comments', 'expanded');

This post by someone else has a decent example: http://www.vagrantradio.com/2009/10/getting-and-setting-cookies-with-jquery.html别人的这篇文章有一个不错的例子: http : //www.vagrantradio.com/2009/10/getting-and-setting-cookies-with-jquery.html

If you can't use jQuery, you need to do standard string parsing like you currently are (perhaps regular expressions instead of the string splitting / replacing might trim down your code) or find some other javascript library that you can use.如果您不能使用 jQuery,您需要像当前一样进行标准字符串解析(也许正则表达式而不是字符串拆分/替换可能会减少您的代码)或找到一些您可以使用的其他 javascript 库。

If you like eye candies in your code you can use a regexp based "search and don't replace" trick by John Resig ( cached here ) :如果您喜欢代码中的糖果,您可以使用 John Resig 的基于正则表达式的“搜索而不替换”技巧( 缓存在此处):

var extract = function(string) {
    var o = {};

    string.replace(/(.*?)=(.*?)(?:\|\||$)/g, function(all, key, value) {
        o[key] = value;
    });

    return o;
};

Then然后

var objects = string.split('++'), 
    i = objects.length;

for (;i--;) {
    objects[i] = extract(objects[i]);
}
var str = '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'
var items = str.split("++");
for (var i=0; i<items.length; i++) {
    var data = items[i].split("||");
    for (var j=0; j<data.length; j++) {
        var stuff = data[j].split("=");
        var n = stuff[0]; 
        var v = stuff[1];
        eval("var "+n+"='"+v+"'");
    }
    alert(id);
}

EDIT: As per JamieC's suggestion, you can eliminate eval("var "+n+"='"+v+"'");编辑:根据 JamieC 的建议,您可以消除eval("var "+n+"='"+v+"'"); and replace it with the (somewhat) safer window[n] = v;并用(有点)更安全的window[n] = v;替换它window[n] = v; -- but you still have the simple problem that this will overwrite existing variables, not to mention you can't tell if the variable color was set on this iteration or if this one skipped it and the last one set it. -- 但是您仍然有一个简单的问题,即这会覆盖现有变量,更不用说您无法判断变量color是否在此迭代中设置,或者是否跳过它而最后一个设置了它。 Creating an empty object before the loop and populating it inside the loop (like every other answer suggests) is a better approach in almost every way.在循环之前创建一个空对象并将其填充到循环内(就像所有其他答案所建议的那样)几乎在所有方面都是更好的方法。

You could do something like this, where you eval the strings when you split them.你可以做这样的事情,在拆分字符串时评估字符串。

<html>
<head>
<script type="text/javascript">
var 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'


var mySplitResult = string.split("||");

for(i = 0; i < mySplitResult.length; i++){
    document.write("<br /> Element " + i + " = " + mySplitResult[i]); 
    var assignment = mySplitResult[i].split("=");

    eval(assignment[0] + "=" + "\""+assignment[1]+"\"");
}
document.write("Price : " + price);
</script>
</head>
<body>
</body>
</html>
JSON.parse('[{' + string.replace(/\+\+/g, '},{').replace(/(\w*)=([\w\s]*)/g, '"$1":"$2"').replace(/\|\|/g, ',') + '}]')

将字符串转换为 JSON 格式,然后解析它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM