Character at index

2 snippets across 2 stacks — JavaScript, SQL

Also written as index of character

JSJavaScript

Repeat and Character Access

JS · Strings
syntax
str.repeat(count)
str.at(index)
example
const border = "=".repeat(30);
console.log(border);

const word = "JavaScript";
console.log(word.at(0));   // "J"
console.log(word.at(-1));  // "t"

Note at() supports negative indices to count from the end. Bracket notation str[-1] returns undefined, not the last character.

SQLSQL

POSITION / STRPOS

SQL · String Functions
syntax
POSITION(substring IN string)
STRPOS(string, substring)  -- PostgreSQL
example
SELECT
  email,
  POSITION('@' IN email) AS at_position,
  SUBSTRING(email FROM POSITION('@' IN email) + 1) AS domain
FROM users;
output
-- email             | at_position | domain
-- [email protected] | 6           | example.com

Note Returns the 1-based position of the first occurrence. Returns 0 if not found (not -1 like most programming languages). MySQL uses LOCATE(substring, string) which has the arguments in reverse order.