slice()

ES3+

Extracts a section of a string and returns it as a new string.

Syntax

string.slice(beginIndex, endIndex)

Parameters

beginIndex number

The index at which to begin extraction

endIndex number optional

The index before which to end extraction

Return Value

string

A new string containing the extracted section

Examples

JavaScript
const str = 'Hello World';
console.log(str.slice(0, 5));
console.log(str.slice(-5));
Output:
// 'Hello' 'World'

📌 When to Use

Use slice() when you need to extract a portion of a string by position. It is the preferred method for substring extraction because it supports negative indices, making it ideal for extracting characters from the end of a string.

⚠️ Common Mistakes

Confusing slice() with splice() - splice() is an array method that modifies the original array, while slice() works on strings and creates a new string.

Forgetting that the end index is exclusive - slice(0, 5) returns characters at positions 0, 1, 2, 3, and 4, not 5.

Not understanding negative indices - slice(-3) returns the last 3 characters, not starting from position -3.

✅ Best Practices

Prefer slice() over substring() because it handles negative indices intuitively and has more predictable behavior.

Use negative indices to extract from the end of strings without calculating the length, e.g., str.slice(-4) for file extensions.

Always validate that your indices are within bounds when working with dynamic string lengths to avoid unexpected empty strings.

⚡ Performance Notes

slice() creates a new string object, which is generally fast as JavaScript engines optimize string operations. However, repeatedly slicing in a loop can create memory pressure. For extracting multiple substrings, consider if a single split() or regex match might be more efficient.

🌍 Real World Example

File Path and Extension Handling

slice() is perfect for extracting file extensions, truncating long text with ellipsis, and working with file paths. The negative index feature makes these operations clean and readable.

// Extract file extension
function getFileExtension(filename) {
  const lastDot = filename.lastIndexOf('.');
  return lastDot === -1 ? '' : filename.slice(lastDot);
}

console.log(getFileExtension('document.pdf')); // '.pdf'
console.log(getFileExtension('archive.tar.gz')); // '.gz'

// Truncate text with ellipsis
function truncate(text, maxLength) {
  if (text.length <= maxLength) return text;
  return text.slice(0, maxLength - 3) + '...';
}

console.log(truncate('Hello World', 8)); // 'Hello...'

// Extract domain from URL
function getDomain(url) {
  const withoutProtocol = url.slice(url.indexOf('//') + 2);
  const domainEnd = withoutProtocol.indexOf('/');
  return domainEnd === -1 ? withoutProtocol : withoutProtocol.slice(0, domainEnd);
}

console.log(getDomain('https://www.example.com/path'));
// Output: 'www.example.com'

Related Methods