Oct 2, 2020

API Testing 'A Beginners View': JavaScript split() Method

strg.split() method is used to split the given string into an array of strings i.e as substrings using a specified separator provided in the argument.

Syntax:

strg.split(separator, limit)


  • separator: (Optional) It is used to specify the regular expression that is being used for splitting the string. If the separator is unspecified then the entire string becomes one single array element. The same also happens when the separator is not present in the string. If the separator is an empty string (“”) then every character of the string is separated.

  • limit: (Optional) Defines the limit on the number of splits to be done in the given string. 

  • Return value: This function returns an array of strings that is formed after splitting the given string at each point where the separator occurs.


Example:

Response Body:











Test Script:

var resp = JSON.parse(responseBody);

//API Testing 'A Beginners View': JavaScript split() Method
    var str = "PostmanRuntime/7.26.8";
    var split_value = str.split("/");
    console.log("user-agent is: " + split_value[1]);
    //Store the split value in an environment variable
    pm.environment.set("user-agent", (split_value[1])); 

Console Output:

user-agent is: 7.26.8


In this example, the function split() splits str wherever ”/“ occurs and returns the index 1 value of the string in variable str.


No comments: