In Javascript, string.substring() returns the part of a string that begins at the start index and ends at the end index.
string.substring(startIndex, endIndex)
const str = 'substring example';
const sub1 = str.substring(0,3);
const sub2 = str.substring(0,5);
const sub3 = str.substring(0,10);
console.log(sub1); // sub
console.log(sub2); // subst
console.log(sub3); // substring
The following example uses the substring() to extract a substring from the index 10 to the end of the string.
const str = 'substring example';
const sub = str.substring(10);
console.log(sub); // example
Using indexOf(), you can find out where the @ character is. After this, the substring returns the domain that starts from the index of @ plus one upwards.
let email = 'example@gmail.com';
let sub = email.substring(email.indexOf('@') + 1);
console.log(sub); // gmail.com
Indexes always begin with 0. If we consider an index to be negative, it will be treated as zero.
const str = 'substring example';
const sub = str.substring(-2,10);
console.log(sub); // substring
Negative numbers are interpreted by slice() as counting from the end of the string when entered as arguments. It will consider a negative value as zero when using substring().
const str = 'substring example';
const sub1 = str.substring(-5);
const sub2 = str.slice(-5);
console.log(sub1); // substring example
console.log(sub2); // ample
In substring, the first argument will be swapped with the second argument if the first argument is greater than the second. Whenever the first argument is greater than the second, slice() returns an empty string.
const str = 'substring example';
const sub1 = str.substring(10,0);
const sub2 = str.slice(10,0);
const sub3 = str.slice(0,10);
console.log(sub1); // substring
console.log(sub2); //
console.log(sub3); // substring
This will remove last element.
const str = 'hello world';
const result = str.substring(0, str.length - 1)
console.log(result); // hello worl
This will print all values between : and ;
const str = 'hello:world;'
const result = str.substring(
str.indexOf(":") + 1,
str.lastIndexOf(";")
);
console.log(result); // world
This will print all values after :
const str = 'one:two'
const result = str.substring(
str.indexOf(":") + 1,
);
console.log(result); // two
This will print all values before :
const str = 'one:two'
const result = str.substring(0, str.indexOf(":"));
console.log(result); // one
This will return the index of the first occurrence.
let str = "one two three four";
let result = str.indexOf("three");
console.log(result); // 8