[英]Javascript RegEx to find string in url between slash and either comma or question mark
我想从以下网址获取javascript返回值“ sct”或“ rain”(将“,20”或“,70”剥离):
<script>
var urls = [
"https://api.weather.gov/icons/land/day/sct,20?size=medium",
"https://api.weather.gov/icons/land/day/sct?size=medium",
"https://api.weather.gov/icons/land/night/rain?size=medium",
"https://api.weather.gov/icons/land/day/rain,60/rain,70?size=medium"
];
for(var key in urls) {
console.log(get_icon(urls[key]));
}
function get_icon(text) {
/* not sure what to do here */
}
</script>
逻辑将在最后一个斜杠之后,逗号或问号之前得到字符串。 我正在用正则表达式声明来做到这一点。
您可以将此正则表达式与.*
的贪婪匹配一起使用,以确保last /
被匹配:
/.*\/([^,?]+)/
([^,?]+)
给您下一个字符串?
或,
在捕获组中。
码:
var urls = [ "https://api.weather.gov/icons/land/day/sct,20?size=medium", "https://api.weather.gov/icons/land/day/sct?size=medium", "https://api.weather.gov/icons/land/night/rain?size=medium", "https://api.weather.gov/icons/land/day/rain,60/rain,70?size=medium" ]; for(var key in urls) { console.log(get_icon(urls[key])); } function get_icon(text) { return (text.match(/.*\\/([^,?]+)/) || [null][null])[1]; }
请检查此正则表达式。 提取组1:
\S+\/(\w+,\d+|\w+)\?\w+=\w+
回复您的需要,我可以做:
function get_icon(text) {
var pos = text.lastIndexOf("/");
var qmark = text.lastIndexOf("?size");
var res = text.substring(pos+1, qmark);
var res = res.split(",");
if (res.length == 2)
return res[1];
else
return null;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.