解析URI中的query string

解析URL中的query string成集合.

前端可以配合使用$.param生成序列化字符串。

JavaScript解析URI中的query string

原生解析

查找指定name的参数值,只会匹配第一个找到的。

1
2
3
4
5
6
7
8
9
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}

qs.js库解析query string

qs.js支持解析 query string,也支持序列化query string,而且qs支持解析query string中的ObjectAarry,前提是按照qs的支持的格式书写。

parse

1
2
var obj = qs.parse('a=c');
assert.deepEqual(obj, { a: 'c' });

stringifying

1
2
var str = qs.stringify(obj);
assert.equal(str, 'a=c');

Java解析编码过的字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static Map<String, List<String>> splitQuery(URL url, String charset) throws UnsupportedEncodingException {
final Map<String, List<String>> queryPairs = new LinkedHashMap<String, List<String>>();
final String[] pairs = url.getQuery().split("&");
for (String pair : pairs) {
final int idx = pair.indexOf("=");
final String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), charset) : pair;
if (!queryPairs.containsKey(key)) {
queryPairs.put(key, new LinkedList<String>());
}
final String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : null;
queryPairs.get(key).add(value);
}
return queryPairs;
}

JDK 8 version

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public Map<String, List<String>> splitQuery(URL url) {
if (Strings.isNullOrEmpty(url.getQuery())) {
return Collections.emptyMap();
}
return Arrays.stream(url.getQuery().split("&"))
.map(this::splitQueryParameter)
.collect(Collectors.groupingBy(SimpleImmutableEntry::getKey, LinkedHashMap::new, mapping(Map.Entry::getValue, toList())));
}

public SimpleImmutableEntry<String, String> splitQueryParameter(String it) {
final int idx = it.indexOf("=");
final String key = idx > 0 ? it.substring(0, idx) : it;
final String value = idx > 0 && it.length() > idx + 1 ? it.substring(idx + 1) : null;
return new SimpleImmutableEntry<>(key, value);
}

common-httpclients.jar

1
2
3
4
5
6
7
8
9
import org.apache.hc.client5.http.utils.URLEncodedUtils
public static void main(String[] args) {
String url = "http://www.example.com/something.html?one=1&two=2&three=3&three=3a";
List<NameValuePair> params = URLEncodedUtils.parse(new URI(url), "UTF-8");

for (NameValuePair param : params) {
System.out.println(param.getName() + " : " + param.getValue());
}
}

Spring Framework

1
2
3
4
5
6
7
8
9
public static void main(String[] args) {
String uri = "http://youhost.com/test?param1=abc&param2=def&param2=ghi";
MultiValueMap<String, String> parameters =
UriComponentsBuilder.fromUriString(uri).build().getQueryParams();
List<String> param1 = parameters.get("param1");
List<String> param2 = parameters.get("param2");
System.out.println("param1: " + param1.get(0));
System.out.println("param2: " + param2.get(0) + "," + param2.get(1));
}

参考链接

Parse a URI String into Name-Value Collection