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.