javascript如何删除字符串的某个部分?

时间:2014-02-15 12:54:58

标签: javascript string cookies replace

我从我的cookie中获取了这个字符串(例子):

Cookies = "link1=whatever; link2=whatever; delete1=true; link3=whatever; delete3=true; link4=whatever;" 

我想删除以delete开头的字符串的最后一部分,以“;”结尾或“”(没什么,刺痛结束)。在这个例子中,我想要 - > delete3 = TRUE; < - 要删除的部分

如何做到这一点?

3 个答案:

答案 0 :(得分:1)

你可以这样做:

Cookies = Cookies.split(';');
var i = Cookies.length,
    r = /^ *delete\d+=/;
while (--i >= 0) {
    if (r.test(Cookies[i])) {
        Cookies.splice(i, 1);
        Cookies = Cookies.join(';');
        break;
    } 
}

更短的方式:

Cookies = Cookies.replace(
    /; *delete\d+=[^;]*(?!.*; *delete\d+=)/, ''
);

更简单(基于Goran.it's answer):

Cookies = Cookies.replace(/(.*;) *delete\d+=.*?;/, '$1');

随时询问详情。

答案 1 :(得分:1)

这是一个简单的正则表达式解决方案:

var Cookies = "link1=whatever; link2=whatever; delete1=true; link3=whatever; delete3=true; link4=whatever;";
var fixed = Cookies.replace(/(.*)(\s?delete.*?;)(.*)$/, '$1$3');

// fixed is now: "link1=whatever; link2=whatever; delete1=true; link3=whatever;  link4=whatever;"

答案 2 :(得分:0)

使用Javascript:

Cookies = "link1=whatever; link2=whatever; delete1=true; link3=whatever; delete3=true; link4=whatever;";

aa = Cookies.split(';');

for (_i = 0, _len = aa.length; _i < _len; _i++) {
  a = aa[_i];
  if (a.trim().search(/^delete/) !== -1) deleters = aa.indexOf(a);
}

aa.splice(deleters, 1);

Cookies = aa.join(';');

CoffeeScript的:

Cookies = "link1=whatever; link2=whatever; delete1=true; link3=whatever; delete3=true; link4=whatever;"
aa=Cookies.split(';')
for a in aa
    deleters=aa.indexOf(a) if a.trim().search(/^delete/)!=-1
aa.splice(deleters, 1)
Cookies = aa.join(';')