Announcement

Collapse
No announcement yet.

Match string values to Array

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Match string values to Array

    I have a string for example myString = " Hi I am a string"
    I have an array with some values that are in the the above string for example:

    myArray[0] = "Hi There"
    myArray[1] = "Kitchen Sink"
    myArray[2] = "stringing it along"

    I need to match any of the values from myString with any values in any of the elements in myArray.

    so from the above myArray[0], and myArray[2] should qualify because myArray[0] has the value "Hi" which is also present in myString, and myArray[2] has the value "stringing" and the "string" part of "stringing" matches with "string" in myString.

    Any ideas would be appreciated.


  • #2
    Maybe a string split, then a nested loop to check for String.match()
    Code:
    myString = myString.split(' ')
    
    for (var i = ...
      for (var j = ...
        if (myArray[i].match(myString[j])) {
         logger.info('match found')
        }
      }
    }
    ...or use the whole regex instead.
    Code:
    for (var i = ...
      if (myArray[i].match(/Hi|I|am|a|string/) {
        logger.info('match found')
      }
    }
    Last edited by jkrebs; 06-30-2020, 07:55 PM.

    Comment


    • #3
      Thanks jkrebs, I actually got it to work with :

      if(myArray.indexOf(myString ) == -1)

      {
      ...
      }


      I have another puzzle...

      Lets say I have an array like so:

      newArray[0] = "KitchenSink, SuperMan, BatMan, TheFlash";
      newArray[1] = "KitchenSink, Thor, Hulk, Wolverine";

      I need to write the contents of the above array into a file. However the issue is that I should only write the values AFTER the first comma in each array element. So the file output should be:
      SuperMan, BatMan, TheFlash
      Thor, Hulk, Wolverine

      "KitchenSink" which comes before the first comma should be ignored.


      Any ideas are appreciated !

      Comment


      • #4
        figured it out.. this works:

        var report = '';
        for (var i = 0; i < newArray.length; i++)
        {
        report += newArray[i].toString().split(',').slice(1) + "\r\n";
        }

        Comment

        Working...
        X