indexOf doesn't match the exact string?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
10-10-2018 04:08 AM
Hi team,
I have a requirement to get the exact string comparison results.
if my condition is like [ if (emailTo.indexOf("networkoperation@test.com") != -1) ]
it will also satisfy the conditions if the email To contains like the following("operation@test.com")
How to find the exact string matching?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
10-11-2018 08:35 AM
Array.indexOf and String.indexOf work differently. In your example, you are using a String and not an Array so you are getting that result (one you do NOT want). String.indexOf is looking for the first occurrence of the search string in your source string.
Running this snippet of code:
var emails = 'networkoperation@test.com, test123@test.com,operation@test.com';
var emailArray = emails.toLowerCase().replace(/\s+/g, '').split(",");
gs.info(emailArray.indexOf("operation@test.com"));
...will return "2" (the third entry in the array) as Array.indexOf will only find exact matches. Array.indexOf searches each individual item in the array to see if they match exactly, so looking for "operation@test.com" in "networkoperation@test.com" is NOT considered a match.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
10-11-2018 08:45 AM
The problem is that the OP wants an EXACT match of strings. indexOf looks for matches within strings.
Example: If I only wanted strings that matched "12345", and I tested "123", indexOf would find a match. But I want it to match 12345 exactly.
Edit: In his/her scenario, if he was looking for "operation@test.com", it would find it twice in the array, since 'networkoperation@test.com' contains "operation@test.com".
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
10-11-2018 09:06 AM
As explained above, indexOf works differently for Strings and Arrays, so an exact match CAN be found using Array.indexOf.
Try running the following script in Background Scripts or Xplore:
var emails = 'networkoperation@test.com, test123@test.com,operation@test.com';
var emailArray = emails.toLowerCase().replace(/\s+/g, '').split(",");
gs.info(emailArray.indexOf("operation@test.com"));
The result is "2", the third item in the array. It does NOT find "networkoperation@test.com" to be a match.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-05-2018 11:17 PM
Did you find a solution to your issue? If yes, please remember to tag the correct answer and any that were helpful.