删除字符串中出现的所有文本

时间:2013-05-21 08:58:43

标签: javascript jquery string

假设我在JavaScript中有一个字符串,如下所示:

var str = "Item%5B9%5D.Something%5B0%5D.Prop1=1&Item%5B9%5D.Something%5B0%5D.Prop2=False&Item%5B9%5D.Something%5B0%5D.Prop3=10%2F04%2F2013+00%3A00%3A00&Item%5B9%5D.Something%5B1%5D.Prop1=2&Item%5B9%5D.Something%5B1%5D.Prop2=False&Item%5B9%5D.Something%5B1%5D.Prop3=10%2F04%2F2013+00%3A00%3A00&Item%5B9%5D.Something%5B2%5D.Prop1=3&Item%5B9%5D.Something%5B2%5D.Prop2=False&Item%5B9%5D.Something%5B2%5D.Prop3=29%2F04%2F2013+00%3A00%3A00&Item%5B9%5D.Something%5B3%5D.Prop1=4&Item%5B9%5D.Something%5B3%5D.Prop2=False&Item%5B9%5D.Something%5B3%5D.Prop3=29%2F04%2F2013+00%3A00%3A00"

并希望它看起来像这样:

var str = "Something%5B0%5D.Prop1=1&Something%5B0%5D.Prop2=False&Something%5B0%5D.Prop3=10%2F04%2F2013+00%3A00%3A00&Something%5B1%5D.Prop1=2&Something%5B1%5D.Prop2=False&Something%5B1%5D.Prop3=10%2F04%2F2013+00%3A00%3A00&Something%5B2%5D.Prop1=3&Something%5B2%5D.Prop2=False&Something%5B2%5D.Prop3=29%2F04%2F2013+00%3A00%3A00&Something%5B3%5D.Prop1=4&Something%5B3%5D.Prop2=False&Something%5B3%5D.Prop3=29%2F04%2F2013+00%3A00%3A00"

即。删除所有项目%5BX%5D。份

我该怎么做呢?我想过使用类似的东西:

str = str.substring(str.indexOf('Something'), str.length);

但显然只会删除第一次出现。

同样,%5B和%5D之间的数字可以是任何数字,不一定是9。

这似乎应该很简单,但出于某种原因,我很难过。我在SO上发现了一些类似的东西,但没有任何东西可以处理上述所有标准。

6 个答案:

答案 0 :(得分:6)

您可以使用正则表达式:

str = str.replace(/Item[^.]+\./g, '');

或者如果你想要更精确的东西,因为你想保留Item%6B3%4D

str = str.replace(/Item%5B.%5D\./g, '');

答案 1 :(得分:4)

str = str.replace('Item%5B9%5D', '');

编辑:错过了字符串中9可以是任意数字的部分。您可以使用:

str = str.replace(/Item%5B\d%5D\./g, '');

答案 2 :(得分:2)

避免使用需要复杂“针”逃逸的正则表达式:

var str =  "something complex full of http://, 'quotes' and more keep1 something complex full of http://, 'quotes' and more keep2 something complex full of http://, 'quotes' and more keep3"
var needle = "something complex full of http://, 'quotes' and more";
 while( str.indexOf(needle) != '-1')
 str = str.replace(needle,"");
 document.write(str);

输出: keep1 keep2 keep3

答案 3 :(得分:1)

你走了:

str = str.replace(/Item%5B\d%5D\./g,'');

Live Demo

答案 4 :(得分:1)

尝试使用正则表达式:

str = str.replace(/Item%5B[^.]*%5D./g, '');

这假设您可以在%5B%5D之间拥有任何长度的任何内容。

JSFiddle

答案 5 :(得分:0)

使用split()join()方法

var str = "Item%5B9%5D.Something%5B0%5D.Prop1=1&Item%5B9%5D.Something%5B0%5D.Prop2=False&Item%5B9%5D.Something%5B0%5D.Prop3=10%2F04%2F2013+00%3A00%3A00&Item%5B9%5D.Something%5B1%5D.Prop1=2&Item%5B9%5D.Something%5B1%5D.Prop2=False&Item%5B9%5D.Something%5B1%5D.Prop3=10%2F04%2F2013+00%3A00%3A00&Item%5B9%5D.Something%5B2%5D.Prop1=3&Item%5B9%5D.Something%5B2%5D.Prop2=False&Item%5B9%5D.Something%5B2%5D.Prop3=29%2F04%2F2013+00%3A00%3A00&Item%5B9%5D.Something%5B3%5D.Prop1=4&Item%5B9%5D.Something%5B3%5D.Prop2=False&Item%5B9%5D.Something%5B3%5D.Prop3=29%2F04%2F2013+00%3A00%3A00";
console.log(str.split(/Item%5B\d%5D\./g).join(''));