Javascript 在Switch station中使用Regex vs includes()方法

Javascript 在Switch station中使用Regex vs includes()方法,javascript,regex,Javascript,Regex,我向OpenWeatherMap.org API发出AJAX请求,以获取本地天气预报(温度、城市和天气描述)。我将天气描述指定给变量“weatherDescription”。我使用switch语句检查“weatherDescription”是否有“clouds”,例如在描述中,它是否将DOM中元素的图像图标更改为“cloudy”图标图像 下面的代码可以在Chrome中使用,但不幸的是.includes()方法不能在其他浏览器(Safari、IE、Opera等)中使用 因此,我现在正在针对regE

我向OpenWeatherMap.org API发出AJAX请求,以获取本地天气预报(温度、城市和天气描述)。我将天气描述指定给变量“weatherDescription”。我使用switch语句检查“weatherDescription”是否有“clouds”,例如在描述中,它是否将DOM中元素的图像图标更改为“cloudy”图标图像

下面的代码可以在Chrome中使用,但不幸的是.includes()方法不能在其他浏览器(Safari、IE、Opera等)中使用

因此,我现在正在针对regExp测试“weatherDescription”,但对于第一种情况,条件总是返回true(下面的示例):


是否有可能实现我在正则表达式中使用.includes()方法得到的相同结果,或者有更好的方法来实现这个目标

问题在于
g
修饰符。对
test
的第二次调用将尝试从上一次匹配开始进行匹配,而不是从字符串的开头开始。JavaScript中的正则表达式对象具有状态,当您将
g
test
exec
等一起使用时,状态非常重要

下面是一个简单的示例,演示了该问题:

var-rex;
rex=/test/g;
snippet.log(rex.test(“test”);//真的
snippet.log(rex.test(“test”);//假的
//vs。
rex=/test/;
snippet.log(rex.test(“test”);//真的
snippet.log(rex.test(“test”);//正确


var myRegExp=/sun | rain | sleet\ig
var myRegExp=/sun | rain | sleet/ig在您的代码中?请注意,您不应该将
test()
g
一起使用。您可以使用RegExp构造函数:oops typo it's myRegExp=/sun | rain | sleet/ig;那么我的第二句话呢?尝试删除
g
并使用
var myRegExp=/sun | rain | sleet/i
@Stribizev我尝试过删除g并使用var myRegExp=/sun | rain | sleet/I;如果RegExp正在测试所有字符串,它将如何区分第一种情况和第二种情况?使用Includes()方法,我根据一个特定的字符串测试每个案例。
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();
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");
}