2

JavaScript Regex, JSON Conversion & Try/Catch for ServiceNow Scripts

In the last topic, you learned about how to store and group data. This topic focuses on making your scripts more reliable by covering three important skills: ensuring data has the right input format, exchanging data with other systems, and handling errors gracefully.

We will cover Regex in JavaScript and the JSON parse and stringify process in this topic. 

Regular Expressions

A regular expression, or Regex in JavaScript, matches character combinations in strings. It helps developers identify user input and whether it is in the correct format. It is written between two forward slashes, /pattern/. For example:

function f1(){

var x= "Abcdefg2";

var regex = /^[A-Z][a-z]{6}[0-9]$/;

if(x.match(regex)){

console.log("username valid");

}

else {

console.log("username not valid");

}

A pattern is made of character classes (what is allowed) and quantifiers (how many times).

Pattern Meaning
[abc] Any one of a, b or c
[^abc] Any character except a, b or c
[a-z] Any lowercase letter
[A-Z] Any uppercase letter
[a-zA-Z] Any letter
[0-9] Any single digit
[$!@#*] Any one of these special characters
{n} Exactly n times, for example [0-9]{7}
{n,m} Between n and m times
+ One or more times
* Zero or more times
? Zero or one time
. Any single character
^ Start of the string
$ End of the string
\. A literal dot. A backslash escapes a special character.

Note: Square brackets create a character class, and the pattern as a whole is built from character classes, quantifiers, and anchors, as the table shows above.

If you want to test the pattern, 

var regex = /^[A-Z][a-z]{6}[0-9]$/;

gs.info(regex.test(‘Abcdefg2’));   // true

gs.info(regex.test(‘abcdefg2’));   // false (starts with lowercase)

JS to JSON & JSON to JS Conversion

JSON, or JavaScript Object Notation, is a format that is similar to code for creating JavaScript objects. This makes it easy to convert JSON data into objects. The JSON values include: 

  • a string
  • a number
  • an object
  • an array
  • a boolean
  • null

Some JSON values do not support the following data types:

  • a function
  • a date object
  • undefined

JS to JSON

JSON is used to exchange data to/from a web server. When you receive data from a web server, it’s always a string. Parse the data with JSON.parse(), and the data becomes a JavaScript object. For Example:

var obj = JSON.parse('{"name":"techtroop", "age":15, "city":"New York"}');

console.log(obj);

O/P: { name: 'techtroop', age: 15, city: 'New York' }

JSON to JS

When sending data to a web server, the data has to be a string. You can convert a JavaScript object into a string with JSON.stringify(). For Example:

var obj = {name: "techtroop", age: 30, city: "New York"};

var myJSON = JSON.stringify(obj);

console.log(myJSON);

O/P: {"name":"techtroop","age":30,"city":"New York"}

Try/Catch

Whenever a script reaches a runtime error, it stops. Try/catch statements let developers handle errors and keep control of what happens. For example, the syntax looks like: 

try {

  // code that might fail

} catch (e) {

  // code that runs only if an error occurs

} finally {

  // optional: code that always runs

}

Here, the try block holds the code that might throw an error. The catch block runs only if an error occurs inside the try block, and the finally block runs every time, whether or not an error occurs. 

Conclusion

JavaScript is a fundamental language of any ServiceNow script. The module focuses on variables, data types, string functions, arrays, objects, regular expressions, and JSON conversion. All this together helps developers read and write scripts in servicenow with the right structure, valid data, and handle errors easily. 

In the next chapter, we will be focusing on client-side scripting in ServiceNow. From basics to how client scripts are written. 

Next Chapter

Need more support?

Get a head start with our FREE study notes!

Learn more and get all the answers you need at zero cost. Improve your skills using our detailed notes prepared by industry experts to help you excel.

SALE IS LIVE
50% OFF