简体   繁体   中英

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). I am assigning the weather description to a variable "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.

The code below works in Chrome but unfortunately the .includes() method does not work in other browsers (Safari, IE, Opera etc).

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) :

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?

The problem is the g modifier. The second call to test will try to match starting from the previous match , not at the beginning of the string. Regular expression objects in JavaScript have state, which matters when you use g with test , exec , and similar.

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM