use string “includes()” in switch Javascript case

前端 未结 4 693
被撕碎了的回忆
被撕碎了的回忆 2021-01-02 06:45

In Javascript, is there a way to achieve something similar to this ?

const databaseObjectID = \"someId\"; // like \"product/217637\"

switch(databaseObjectID         


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-02 07:21

    Question:

    use string “includes()” in switch Javascript case

    While the includes() method will work, it is case sensitive, and just matches any characters. I have found a Regex solution that I like much better, and provides a lot of flexibility. For example, you could easily change this to match only WORDS.

    var sourceStr = 'Some Text and literaltextforcase2 and more text'
    
    switch (true)  {  // sourceStr
    
      case (/LiteralTextForCase1/i.test(sourceStr)):
          console.log('Case 1');
          break;
    
      case (/LiteralTextForCase2/i.test(sourceStr)):
        console.log('Case 2');
        break;
    
      default:
          console.log('ERROR No Case provided for: ' + sourceStr);
    };
    
    //-->Case 2

提交回复
热议问题