我有以下字符串响应,我将其存储在变量中。
TotalHTTP/1.1 200 OK,Cache-Control: max-age=900, public,Connection: keep-alive,Date: Fri, 19 Dec 2014 06:54:04 GMT,Content-Length: 28359,Content-Type: text/html; charset=utf-8,a:b,
我想提取特定字符串的响应并将其存储在一个单独的变量中进行打印。
例如..如果我必须提取Cache-Control的响应,我该怎么办? max-age = 900,public
尝试使用split,indexof和其他一些方法,但没有任何效果。
答案 0 :(得分:1)
使用正则表达式匹配:
var Response = "TotalHTTP/1.1 200 OK,Cache-Control: max-age=900, public,Connection: keep-alive,Date: Fri, 19 Dec 2014 06:54:04 GMT,Content-Length: 28359,Content-Type: text/html; charset=utf-8,a:b,",
CacheControlRegEx = /Cache-Control:\s(.+?),/,
CacheControl = false;
if (CacheControl = CacheControlRegEx.exec(Response)){
CacheControl = CacheControl[1];
}
答案 1 :(得分:1)
使用拆分功能正常工作,使用以下代码。
var response = "TotalHTTP/1.1 200 OK,Cache-Control: max-age=900, public,Connection: keep-alive,Date: Fri, 19 Dec 2014 06:54:04 GMT,Content-Length: 28359,Content-Type: text/html; charset=utf-8,a:b,";
var splitted = response.split(",");
var cache_splitted = splitted[1].split(":");
var cache_val = cache_splitted[1];
答案 2 :(得分:1)
您需要使用多个拆分:
var string = "TotalHTTP/1.1 200 OK,Cache-Control: max-age=900, public,Connection: keep-alive,Date: Fri, 19 Dec 2014 06:54:04 GMT,Content-Length: 28359,Content-Type: text/html; charset=utf-8,a:b,";
var all = {};
/* First split the string at the comma */
string = string.split(",");
/* Now loop through the created array */
for(var o = 0; o < string.length; o++){
/* Splitting each element again, this time at the `:` */
var temp = string[o].split(":");
/* And assigning the first in the temporary element as the key
* And then either a value or an empty string. I used .trim() to
* make it easier, it could be even easier if you
* use .toLowerCase() so you can't make typos. */
all[temp[0].trim()] = temp[1] || "";
}
现在你可以通过
来询问任何事物的价值all["Cache-Control"];
<script type="text/javascript">
var string = "TotalHTTP/1.1 200 OK,Cache-Control: max-age=900, public,Connection: keep-alive,Date: Fri, 19 Dec 2014 06:54:04 GMT,Content-Length: 28359,Content-Type: text/html; charset=utf-8,a:b,";
var all = {};
/* First split the string at the comma */
string = string.split(",");
/* Now loop through the created array */
for(var o = 0; o < string.length; o++){
/* Splitting each element again, this time at the `:` */
var temp = string[o].split(":");
/* And assigning the first in the temporary element as the key
* And then either a value or an empty string. I used .trim() to
* make it easier, it could be even easier if you
* use .toLowerCase() so you can't make typos. */
all[temp[0].trim()] = temp[1] || "";
}
document.write("Cache-Control contains: " + all["Cache-Control"])
</script>
&#13;
你可以在temp [1]元素中进行另一次拆分,将max-age = 900分开,这样你就可以做更详细的事情,但是这样做。