Useful JavaScript Methods

jesusemelendezm
Mega Guru

I am creating a list of useful JavaScript methods to accomplish multiple tasks in ServiceNow. Those methods that should be unforgettable and kept handy to use in any scripting area of ServiceNow.

Just today while working with date fields and inbound rules, I used three useful methods toLowerCase(), indexOf() and getNumericValue(). The toLowerCase() and IndexOf() methods to set a condition for an inbound action to   run only when a certain email address was found in the recipients. This was the condition: email.recipients.toLowerCase().indexOf('email01@company.com')   > -1

The getNumericValue() method was very useful when I was intending to compare two date fields. The statement that I wrote was the following: var task_due_date = current.due_date.getGlideObject().getNumericValue(); // this returns the int value of the date and I could easily compare it against another variable that had stored int value from another date type field.

Please share!

Thank you.

5 REPLIES 5

bernyalvarado
Mega Sage

Hi Jesus, here goes some basic ones that may be helpful for your list:



.toString(); // Cast a value to a string format


parseInt(); // Method to cast to a Integer


isNaN(); // Check if a value is not a valid number


gel(); // Get element by id. Used to grab the element on the client side




Thanks,


Berny


bernyalvarado
Mega Sage

Oh, and since you liked/learned about indexOf, it may also be of help to know that there's also a .lastIndexOf() function that could be useful for you in the future. This is useful specially when having to lookup/navigate in strings or arrays.



The following links provide a handful list of useful string and array methods, which are the ones we mostly have to deal with in ServiceNow:



JavaScript String Methods


JavaScript Array Methods



Thanks,


Berny


Deepak Ingale1
Mega Sage

.length - Property and not a method to get the length of string variable


.count - Property to get how many members are there in an array.



Also, if you want to use indexOf for array, you will have to use the "ArrayUtil" script include of the servicenow.



e.g.


var arrayVar = ['a','b','c'] ;


gs.print(arrayVar.indexOf('a')) ; // this will print -1 as if element a is not a part of array.



WhereAS



var arrayVar = ['a','b','c'] ;


var arrayUtilVar = new ArrayUtil();


gs.print(arrayUtilVar.indexOf(arrayVar , 'a')) ; // this will print 0 which indicates a is at 0th position in array variable arrayUtilVar


Slava Savitsky
Giga Sage