FIND YOUR NEXT FEW LINES

The snippet library.

Small, practical examples. Search by task or narrow things down below.

125 snippets foundClear filters
JavaScriptGetting Started

Read one character from ASCII text

JavaScript: Use a valid zero-based index to read the first character.

JavaScript✓ Tested
JavaScriptGetting Started

Read the beginning of a text value

JavaScript: Extract or display the first three ASCII characters from a known nonempty string.

JavaScript✓ Tested
JavaScriptArray traversal & selection

Read the final array item with a negative index

JavaScript: at supports negative positions counted from the end.

JavaScript✓ Tested
JavaScriptGetting Started

Read the first collection element

JavaScript: Access index zero only after establishing that the collection is nonempty.

JavaScript✓ Tested
JavaScriptPromises & iteration protocols

Recover from an expected promise rejection

JavaScript: Return a fallback from catch so later handlers receive an ordinary resolved value.

JavaScript✓ Tested
JavaScriptObject behavior & collections

Remove a Map entry and detect whether it existed

JavaScript: Map.delete returns true only when an entry was present.

JavaScript✓ Tested
JavaScriptArrays

Remove duplicate values

Use a JavaScript Set to preserve the first occurrence of each primitive value.

JavaScript✓ Tested
JavaScriptRegular expressions & URL encoding

Reorder captured text in a replacement

JavaScript: Use numbered replacement groups to rearrange a known two-part name.

JavaScript✓ Tested
JavaScriptGetting Started

Repeat a fixed number of times

JavaScript: Use a counted loop to print three numbered steps.

JavaScript✓ Tested
JavaScriptText handling & Unicode

Repeat a string a fixed number of times

JavaScript: String.repeat requires a nonnegative finite repetition count.

JavaScript✓ Tested
JavaScriptGetting Started

Repeat while a condition holds

JavaScript: Count down while a positive number remains, updating the loop variable on each iteration.

JavaScript✓ Tested
JavaScriptStrings

Replace all literal matches

Replace repeated substrings with JavaScript replaceAll.

JavaScript✓ Tested