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.

Frequently asked questions

How do you extract part of string?
This task is covered in 2 stacks on this page: JavaScript, 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 "extract part of string" on this page?
JavaScript, SQL. Together they hold 2 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.