3

假设我在 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"

即删除所有Item%5BX%5D。部分

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

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

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

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

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

4

6 回答 6

6

您可以使用正则表达式:

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

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

str = str.replace(/Item%5B.%5D\./g, '');
于 2013-05-21T09:00:31.703 回答
4
str = str.replace('Item%5B9%5D', '');

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

str = str.replace(/Item%5B\d%5D\./g, '');
于 2013-05-21T09:01:19.857 回答
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

于 2013-10-23T15:04:46.633 回答
1

干得好:

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

现场演示

于 2013-05-21T09:07:38.457 回答
1

尝试使用正则表达式:

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

%5B这假设您可以在和之间有任何长度%5D

JSFiddle

于 2013-05-21T09:07:47.530 回答
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(''));

于 2020-06-19T10:39:27.350 回答