Is it possible to use .contains() in a switch statement?

后端 未结 2 443
萌比男神i
萌比男神i 2021-01-03 19:18

This is just a simple example of what I\'m trying to do:

switch (window.location.href.contains(\'\')) {
    case \"google\":
        searchWithGoogle();
             


        
2条回答
  •  独厮守ぢ
    2021-01-03 19:52

    An alternative implementation might be this. Not much in it but reads better than switch(true)...

    const href = window.location.href;
    const findTerm = (term) => {
      if (href.includes(term)){
        return href;
      }
    };
    
    switch (href) {
      case findTerm('google'):
          searchWithGoogle();
          break;
      case findTerm('yahoo'):
          searchWithYahoo();
          break;
      default:
          console.log('No search engine found');
    };
    

提交回复
热议问题