JavaScript String substring()

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

substring() Syntax Top ↑

string.substring(indexStart)
string.substring(indexStart, indexEnd)

Extract from One Index to the End Top ↑

const text = "JavaScript";
console.log(text.substring(4)); // Script

Extract Between Start and End Indexes Top ↑

The end index itself is not included.

const text = "JavaScript";
console.log(text.substring(0, 4)); // Java

If Start Is Greater Than End, substring() Swaps Them Top ↑

const text = "JavaScript";
console.log(text.substring(4, 0)); // Java

This is different from slice(4, 0), which returns an empty string.

Negative Values Are Treated as 0 Top ↑

const text = "JavaScript";
console.log(text.substring(-3, 4)); // Java

substring() vs slice() Top ↑

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.

substring() vs Legacy substr() Top ↑

substr() uses start, length. substring() uses start, end. The similar names are a common source of mistakes.

Extract the Domain Label from an Email-Like String Top ↑

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.

Common substring() Mistakes Top ↑

  • Expecting the end index to be included.
  • Confusing the second argument with a character count.
  • Expecting negative indexes to count from the end.
  • Forgetting that reversed arguments are swapped.
  • Confusing substring() with legacy substr().

String Reference indexOf()




Subscribe to our YouTube Channel here



plus2net.com







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?



✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer