Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

indexOf doesn't match the exact string?

gokulraj
Giga Expert

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?

18 REPLIES 18

If you are looking for an exact match then you can simply check like :

 

 if (emailTo=="networkoperation@test.com") 

 

Harsh Vardhan
Giga Patron

i have tested and it will work..

it will work for the exact condition

 

var emails='networkoperation@test.com';
if (emails.startsWith("operation@test.com"))
{

gs.print('hello');
}
else
{
gs.print('not hello');
}

 

 

find_real_file.png

Jim Coyne
Kilo Patron

I'm not 100% sure what it is you are asking, but you could use the native array.indexOf method to easily look for a matching email address in an array:

var emails = 'networkoperation@test.com, operation@test.com';
var emailArray = emails.toLowerCase().replace(/\s+/g, '').split(",");  //create an array from the comma-separated string, forced to lowercase first
gs.info(emailArray.indexOf("operation@test.com") > -1);

...should return "true" for you.

If running in an instance before Helsinki (I'm assuming not), you can also use the "contains" method in the ArrayUtil Script Include:

var emails = 'networkoperation@test.com, operation@test.com';
var emailArray = emails.toLowerCase().replace(/\s+/g, '').split(",");  //create an array from the comma-separated string, stripping all spaces and forcing to lowercase first
var arrayUtil = new ArrayUtil();
gs.info(arrayUtil.contains(emailArray, "operation@test.com"));

...would return "true" as well.

Hey Jim,

Like you said array.indexOf method will give the match,but some cases it fails,

For E.g,

var emails='networkoperation@test.com ';
if (emails.indexOf("operation@test.com")>-1)
{

gs.print('hello');
}

In this case it will match the if condition,

So to avoid this I want to match the exact string..

You may want to try looping through the email array and comparing the emails that way:

 

var emails = 'networkoperation@test.com, operation@test.com';
var emailArray = emails.toLowerCase().replace(/\s+/g, '').split(",");

for(var i = 0; i < emailArray.length; i++){
	if(emailArray[i] == 'networkoperation@test.com'){
	//do something if they match
	}
}