substring() returns part of a string between a start index and an optional end index. The start is included and the end is excluded.
const text = "Welcome to plus2net.com";
console.log(text.substring(11, 19)); // plus2net
string.substring(indexStart)
string.substring(indexStart, indexEnd)
const text = "JavaScript";
console.log(text.substring(4)); // Script
The end index itself is not included.
const text = "JavaScript";
console.log(text.substring(0, 4)); // Java
const text = "JavaScript";
console.log(text.substring(4, 0)); // Java
This is different from slice(4, 0), which returns an empty string.
const text = "JavaScript";
console.log(text.substring(-3, 4)); // Java
slice() supports negative indexes that count from the end and does not swap reversed arguments. substring() clamps negative values to 0 and swaps start/end when necessary.
substr() uses start, length. substring() uses start, end. The similar names are a common source of mistakes.
The original page combined indexOf() and substring(). This keeps the example but finds the dot after the @, which is safer than simply taking the first dot anywhere in the address.
const email = "userid@example.com";
const start = email.indexOf("@") + 1;
const end = email.indexOf(".", start);
const domainLabel = email.substring(start, end);
console.log(domainLabel); // example
For broader examples, see indexOf() and email string processing.
substring() with legacy substr().Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| Noel | 16-09-2012 |
| How can split an email into parts before(userID) and after (Domain) the @ sign, and then validate to see if each of these parts are valid? | |