Slice string

3 snippets across 3 stacks - JavaScript, Python, SQL

JSJavaScript

Extracting Substrings

JS · Strings
Syntax
str.slice(start, end)
str.substring(start, end)
Example
const path = "/users/profile/avatar.png";
console.log(path.slice(1));          // "users/profile/avatar.png"
console.log(path.slice(-10));        // "avatar.png"
console.log(path.slice(7, 14));      // "profile"

Note slice() supports negative indices (counts from end). substring() does not. Prefer slice() -- it is more predictable.

PYPython

String Slicing

PY · Strings
Syntax
string[start:stop:step]
Example
word = "pythonic"
print(word[0:4])
print(word[-4:])
print(word[::2])
print(word[::-1])
Output
pyth
onic
ptoi
cinohtyp

Note Slicing never raises IndexError, even if indices exceed the string length. Negative step reverses direction.

SQLSQL

SUBSTRING

SQL · String Functions
Syntax
SUBSTRING(string FROM start FOR length)
SUBSTRING(string, start, length)
Example
SELECT
  SUBSTRING(phone FROM 1 FOR 3) AS area_code,
  SUBSTRING(email FROM POSITION('@' IN email) + 1) AS domain
FROM users;
Output
-- area_code | domain
-- 206       | example.com

Note Positions are 1-based in SQL (not 0-based like most programming languages). The FROM/FOR syntax is ANSI; the comma syntax works in MySQL and PostgreSQL.

Frequently asked questions

How does JavaScript handle slice string?
This task is covered in 3 stacks on this page: JavaScript, Python, SQL. The "Extracting Substrings" snippet in JavaScript uses `str.slice(start, end)`.
Which code does the JavaScript example use?
The "Extracting Substrings" snippet uses `str.slice(start, end)`, from the Strings section of the JavaScript cheat sheet.
Which stacks cover "slice string" on this page?
JavaScript, Python, SQL. Together they hold 3 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Extracting Substrings": slice() supports negative indices (counts from end). substring() does not. Prefer slice() -- it is more predictable.