我希望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>
逻辑将在最后一次斜杠之后和逗号或问号之前获取字符串。我正在努力使用正则表达式来做到这一点。
答案 0 :(得分:2)
您可以将此正则表达式与.*
的贪婪匹配结合使用,以确保匹配上一个/
:
/.*\/([^,?]+)/
([^,?]+)
会在捕获组中的下一个?
或,
之前为您提供字符串。
<强>代码:强>
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 :(得分:0)
请检查此正则表达式。提取第1组:
employees.aggregate(
[{ "$match":
{"$and": [
{"$or": [
{name : { "$regex": param, "$options":"i"}},
{title : { "$regex": param, "$options":"i"}},
]},
{ tenure : true }
]}
},
{"$sort":{experience : -1}},
{"$limit" : 100}
])
答案 2 :(得分:0)
回复你的需要,我可以这样做:
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;
}