[英]Using Regex vs includes() method with Switch Statment
I making an AJAX request to OpenWeatherMap.org API to get the local weather forecast (temp, city, and weather description). 我向OpenWeatherMap.org API发出AJAX请求,以获取本地天气预报(温度,城市和天气描述)。 I am assigning the weather description to a variable "weatherDescription".
我将天气描述分配给变量“ weatherDescription”。 I am using a switch statement to check if "weatherDescription" has "clouds" for example in the description and if it does changing the icon of an image of a element within the DOM to a "cloudy" icon image.
我正在使用switch语句检查“ weatherDescription”在说明中是否具有“ clouds”,并且是否确实将DOM中元素的图像图标更改为“ cloudy”图标图像。
The code below works in Chrome but unfortunately the .includes() method does not work in other browsers (Safari, IE, Opera etc). 以下代码可在Chrome中运行,但不幸的是.includes()方法在其他浏览器(Safari,IE,Opera等)中无法使用。
function SwitchIcons() {
switch (true) {
case (weatherDescription.includes('clear')):
icon.className = "";
icon.classList.add("wi", "wi-day-sunny");
break;
case (weatherDescription.includes('rain')):
icon.className = "";
icon.classList.add("wi", "wi-day-rain");
}
}
SwitchIcons();
So, I am now testing "weatherDescription" against a regExp but the condition always returns true for the first case (example below) : 因此,我现在正在针对regExp测试“ weatherDescription”,但对于第一种情况(以下示例),条件始终返回true:
var myRegExp = /sun|rain|sleet/ig;
switch (true) {
case myRegExp.test(weatherDescription)):
icon.className = "";
icon.classList.add("wi", "wi-day-sunny");
break;
case myRegExp.test(weatherDescription)):
icon.className = "";
icon.classList.add("wi", "wi-day-rain");
}
Is it possible to accomplish the same results I was receiving using .includes() method with regEx or is there a better way of accomplishing this goal? 是否可以使用regEx使用.includes()方法获得与我收到的结果相同的结果,还是有更好的方法实现这一目标?
The problem is the g
modifier. 问题是
g
修饰符。 The second call to test
will try to match starting from the previous match , not at the beginning of the string. 第二次调用
test
将尝试从上一个匹配开始匹配 ,而不是从字符串开头开始匹配。 Regular expression objects in JavaScript have state, which matters when you use g
with test
, exec
, and similar. JavaScript中的正则表达式对象具有状态,当您将
g
与test
, exec
一起使用时,状态很重要。
Here's a simpler example demonstrating the problem: 这是一个更简单的示例来说明问题:
var rex; rex = /test/g; snippet.log(rex.test("test")); // true snippet.log(rex.test("test")); // false // vs. rex = /test/; snippet.log(rex.test("test")); // true snippet.log(rex.test("test")); // true
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.