STRING

JavaScript String split() method

str.split() method is used to split the given string into array of strings by separating it into substrings using a specified separator provided in the argument.

Syntax :

str.split(separator, limit)

separator - It is used to specify the character, or the regular expression, to use 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 - Defines the upper limit on the number of splits to be found in the given string. If the string remains unchecked after the limit is reached then it is not reported in the array.

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

Example :

// Without limit
let str = "Hello world Happy morning"
let array = str.split(" ");
console.log(array);
//Prints: ["Hello", "world", "Happy", "morning"]
// With limit
let str = "Hello world Happy morning"
let array = str.split(" ", 2);
console.log(array);
//Prints: ["Hello", "world"]

toString() :

The toString() method returns the value of a String object.

Syntax :

string.toString()

Example :

let str = "Hello World";
let array = str.toString();
console.log(array);
//Prints: Hello World
let colors = ["Red", "Green", "Blue"];
console.log(colors.toString())
//Prints: Red, Green, Blue

charAt() :

The charAt() method returns the character at the specified index in a string. The index of the first character is 0, the second character is 1, and so on. The index of the last character in a string is string.length-1, the second last character is string is string.length-2 and so on.

Syntax :

string.charAt(index)

index - An integer representing the index of the character you want to return

Example :

let str = "Hello World";
let res = str.charAt(0);
console.log(res);
//Prints: H
console.log(str.chatAt(str.length-1);
//Prints: d