Examples

Examples · Strings

JavaScript String Examples

A runnable cookbook of everyday string tasks — reverse, capitalize, search, replace, split, trim, pad and more — each a short snippet you can run in the browser.

XCODXExamples · Updated

Overview

Short, copy-paste examples for the most common things you do with strings in JavaScript. Every snippet runs — edit any of them in the online JavaScript compiler. For the mechanics behind a method, follow the links to its reference page.

Examples

Reverse a string

const reversed = [...'hello'].reverse().join('');
console.log(reversed); // 'olleh'

Capitalize the first letter

const s = 'hello world';
console.log(s[0].toUpperCase() + s.slice(1)); // 'Hello world'

Check if a string contains text

const url = 'https://xcodx.io';
console.log(url.includes('xcodx'));   // true
console.log(url.startsWith('https')); // true

Replace all occurrences

console.log('a-b-c'.replaceAll('-', '_')); // 'a_b_c'
console.log('a-b-c'.replace(/-/g, '_'));   // 'a_b_c'

Split into words

const words = 'one  two   three'.split(/\s+/);
console.log(words); // ['one', 'two', 'three']

Trim and normalise whitespace

const raw = '   Hello   world   ';
console.log(raw.trim().replace(/\s+/g, ' ')); // 'Hello world'

Pad a number with zeros

console.log(String(7).padStart(3, '0'));  // '007'
console.log('5'.padEnd(3, '.'));          // '5..'

Repeat a string

Count occurrences of a character

const text = 'banana';
const n = [...text].filter(c => c === 'a').length;
console.log(n); // 3

Convert to a URL slug

const title = 'Hello, World! 2026';

const slug = title
  .toLowerCase()
  .replace(/[^a-z0-9]+/g, '-')  // non-alphanumerics → dashes
  .replace(/^-+|-+$/g, '');     // trim leading/trailing dashes

console.log(slug); // 'hello-world-2026'

Join an array into a string

const parts = ['2026', '08', '02'];
console.log(parts.join('-')); // '2026-08-02'

Interpolate values with a template literal

const user = 'Ada';
const count = 3;
console.log(`${user} has ${count} item${count === 1 ? '' : 's'}`); // 'Ada has 3 items'

Truncate long text with an ellipsis

function truncate(str, max) {
  return str.length > max ? str.slice(0, max).trimEnd() + '…' : str;
}

console.log(truncate('the quick brown fox', 12)); // 'the quick…'

Frequently asked questions

How do I reverse a string in JavaScript?
Spread into characters, reverse the array, and join: [...str].reverse().join(''). See the how-to for the emoji-safe details.
How do I replace every occurrence of a substring?
Use str.replaceAll('old', 'new'), or a global regex str.replace(/old/g, 'new'). A plain string passed to replace() changes only the first match.
How do I capitalize the first letter of a string?
Upper-case the first character and append the rest: s[0].toUpperCase() + s.slice(1).