Extract part of string

2 snippets across 2 stacks — JavaScript, 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.

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.