JavaScript startsWith() to Check a String Prefix

Use text.startsWith(prefix) to check whether a JavaScript string starts with a specific sequence. It returns true for a match and false otherwise. Pass position to require the match to start at that index.

Check whether a string starts with a prefix

Case and spaces are significant. An empty prefix always matches, so handle empty input first if a prefix is required. Passing a regular expression throws TypeError. See ECMAScript · String.prototype.startsWith() for the rules.

console.log('JavaScript'.startsWith('Java')); // true
console.log('JavaScript'.startsWith('Script')); // false
console.log('JavaScript'.startsWith('java')); // false
console.log(' JavaScript'.startsWith('Java')); // false
console.log('JavaScript'.startsWith('')); // true
try {
  'JavaScript'.startsWith(/Java/);
} catch (error) {
  console.log(error.name); // TypeError
}

Check for a match at position

The default position is 0. JavaScript converts a supplied value to an integer and clamps it between 0 and text.length. In abzcd, index 2 is z. Index 1 is b, so the same prefix fails there.

const text = 'abzcd';
console.log(text.startsWith('z'));     // false
console.log(text.startsWith('z', 2));  // true
console.log(text.startsWith('z', 1));  // false
console.log(text.includes('z', 1));    // true
console.log(text.startsWith('z', 2.9)); // true
console.log(text.startsWith('a', -1));  // true
console.log(text.startsWith('z', 99));  // false
console.log('A🙂Z'.startsWith('Z', 3)); // true
console.log('A🙂Z'.startsWith('Z', 2)); // false

Positions count UTF-16 code units. In 'A🙂Z', Z is at index 3. Use includes() to search for a substring to search anywhere from a position, or endsWith() to check a suffix to compare against an end boundary.

Match a URL path prefix

To classify a URL under a documentation section, parse the address with URL and check pathname. The trailing slash in /docs/ distinguishes it from /docs-old. Add an exact comparison if the bare path /docs belongs in the section too.

const address = new URL('https://example.com/docs/intro');

function isDocsPath(path) {
  return path === '/docs' || path.startsWith('/docs/');
}

console.log(isDocsPath(address.pathname)); // true
console.log(isDocsPath('/docs'));           // true
console.log(isDocsPath('/docs-old'));       // false

console.log(address.origin === 'https://example.com'); // true

This check groups paths. For an HTTP or HTTPS origin check, compare the parsed origin with the allowed origin exactly. The scheme, host, and port determine the origin. URL Standard · URL.origin

Change the match position in an HTML example

Save the code below as string-starts-with.html using UTF-8 and open it in a browser. The initial result for abzcd and z is false. Enable the position to test zcd at the default index 2 and get true. Change it to 1 to test bzcd and get false.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>String prefix check</title>
</head>
<body>
<label for="text">Original string</label>
<input id="text" type="text" value="abzcd">
<label for="prefix">Prefix</label>
<input id="prefix" type="text" value="z">
<label><input id="use-position" type="checkbox"> Use a match position</label>
<label for="position">Match position</label>
<input id="position" type="number" min="0" step="1" value="2" disabled>
<pre id="output" aria-live="polite"></pre>
<script>
const text = document.querySelector('#text');
const prefix = document.querySelector('#prefix');
const usePosition = document.querySelector('#use-position');
const position = document.querySelector('#position');
const output = document.querySelector('#output');

function show() {
  position.disabled = !usePosition.checked;
  const index = Number(position.value);
  if (usePosition.checked && (position.value.trim() === '' ||
      !Number.isInteger(index) || index < 0)) {
    output.textContent = "Enter a non-negative integer for the match position.";
    return;
  }
  const value = text.value;
  const target = prefix.value;
  const part = usePosition.checked ? value.slice(index) : value;
  const found = usePosition.checked
    ? value.startsWith(target, index) : value.startsWith(target);
  output.textContent = `Checked text: ${JSON.stringify(part)}\n` +
    `Prefix: ${JSON.stringify(target)}\n` +
    `startsWith() result: ${found}`;
}

text.addEventListener('input', show);
prefix.addEventListener('input', show);
usePosition.addEventListener('change', show);
position.addEventListener('input', show);
show();
</script>
</body>
</html>

While the position is enabled, a blank, negative, or fractional entry shows a message. Turn the option off to check from the beginning again. Clear the prefix to see the empty match.