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.

Frequently asked questions

How does JavaScript handle character at index?
This task is covered in 2 stacks on this page: JavaScript, SQL. The "Repeat and Character Access" snippet in JavaScript uses `str.repeat(count)`.
Which code does the JavaScript example use?
The "Repeat and Character Access" snippet uses `str.repeat(count)`, from the Strings section of the JavaScript cheat sheet.
Which stacks cover "character at index" on this page?
JavaScript, SQL. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Repeat and Character Access": at() supports negative indices to count from the end. Bracket notation str[-1] returns undefined, not the last character.