Wildcard string comparison in Javascript

后端 未结 7 2135
花落未央
花落未央 2020-12-01 06:00

Let\'s say I have an array with many Strings Called \"birdBlue\", \"birdRed\" and some other animals like \"pig1\", \"pig2\"

相关标签:
7条回答
  • 2020-12-01 06:57

    You could use Javascript's substring method. For example:

    var list = ["bird1", "bird2", "pig1"]
    
    for (var i = 0; i < list.length; i++) {
      if (list[i].substring(0,4) == "bird") {
       console.log(list[i]);
      }
    }
    

    Which outputs:

    bird1
    bird2
    

    Basically, you're checking each item in the array to see if the first four letters are 'bird'. This does assume that 'bird' will always be at the front of the string.


    So let's say your getting a pathname from a URL :

    Let's say your at bird1?=letsfly - you could use this code to check the URL:

    var listOfUrls = [
                      "bird1?=letsfly",
                      "bird",
                      "pigs?=dontfly",
                     ]
    
    for (var i = 0; i < list.length; i++) {
      if (listOfUrls[i].substring(0,4) === 'bird') {
        // do something
      }
    }
    

    The above would match the first to URL's, but not the third (not the pig). You could easily swap out url.substring(0,4) with a regex, or even another javascript method like .contains()


    Using the .contains() method might be a little more secure. You won't need to know which part of the URL 'bird' is at. For instance:

    var url = 'www.example.com/bird?=fly'
    
    if (url.contains('bird')) {
      // this is true
      // do something
    }
    
    0 讨论(0)
提交回复
热议问题