How to define 'contains' in an IF conditions

JLeong
Mega Sage

HI Guys,

Quick question, what is the operator for 'contains'?

My condition is: if category contains 'Europe'

How do I translate that?

I tried - if(categoryLikeEurope), it didnt work.

Thank you!

1 ACCEPTED SOLUTION

Alberto Consonn
ServiceNow Employee
ServiceNow Employee

Hi,

you have to use the function indexOf.

Please check below an example:

var str = "Hello world, welcome to the universe.";
var n = str.indexOf("welcome");

JavaScript String indexOf() Method

Check also the example in the thread below, it will help you to understand how to use the indexOf in an IF condition:

https://community.servicenow.com/community?id=community_question&sys_id=aadc8729db9cdbc01dcaf3231f96...

If I have answered your question, please mark my response as correct so that others with the same question in the future can find it quickly and that it gets removed from the Unanswered list.

Thank you

Cheers
Alberto

View solution in original post

7 REPLIES 7

Alberto Consonn
ServiceNow Employee
ServiceNow Employee

Hi,

you have to use the function indexOf.

Please check below an example:

var str = "Hello world, welcome to the universe.";
var n = str.indexOf("welcome");

JavaScript String indexOf() Method

Check also the example in the thread below, it will help you to understand how to use the indexOf in an IF condition:

https://community.servicenow.com/community?id=community_question&sys_id=aadc8729db9cdbc01dcaf3231f96...

If I have answered your question, please mark my response as correct so that others with the same question in the future can find it quickly and that it gets removed from the Unanswered list.

Thank you

Cheers
Alberto

Just to expand on what Alberto has said; indexOf will return a number value indicating where in a given string your syntax is located. This is 0 numbered so in the string 'Hello World' indexOf('Hello') would return 0 as the syntax appears at the start of the string. It will return -1 if the syntax is not found.

If you want to use indexOf in an if statement you will need use an operator to define if the syntax is there or not eg:

if(str.indexOf('Hello') > -1){ //if the returned value is greater than -1 then the syntax exists in the string.

//do stuff

}

Thanks for the explanation David! This works!

This works! Thank you Alberto!