Extract parts of a JavaScript string with substring() and compare slice()
text.substring(start, end) extracts the range from the start up to but excluding the end. Omit the end for the rest of the string. The original stays unchanged.
Include the start and exclude the end
Indexes start at zero. substring(1, 4) copies positions 1 through 3, and equal indexes give an empty string. The second argument is an end index. The legacy substr() takes a length instead. See substr() and String.prototype.substring().
const text = '123456789';
console.log(text.substring(1, 4)); // '234'
console.log(text.substring(0, 4)); // '1234'
console.log(text.substring(2)); // '3456789'
console.log(text.substring(3, 3)); // ''
console.log(text);
Compare reversed and negative bounds with slice()
substring() clamps negative indexes to zero and oversized indexes to the string length. It then swaps reversed bounds. slice() counts negative indexes from the end and returns an empty string for reversed bounds after normalization. Decide whether to accept reversed input before calling substring().
console.log('abcdef'.substring(4, 1)); // 'bcd'
console.log('abcdef'.substring(-2, 2)); // 'ab'
console.log('abcdef'.substring(3, 99)); // 'def'
console.log('abcdef'.slice(4, 1)); // ''
console.log('abcdef'.slice(-2)); // 'ef'
Try the complete range example
Save the code in UTF-8 as substring-example.html and open it. With the default text, both 1 to 4 and 4 to 1 produce '234'. Start at 2 and leave the end blank to get '3456789'. Reset restores the fields and result, while the source never changes.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Practice substring ranges</title>
</head>
<body>
<label for="source">Original string</label>
<input id="source" type="text" value="123456789">
<label for="start">Start index</label>
<input id="start" type="number" step="1" value="1">
<label for="end">End index (exclusive, blank for the remainder)</label>
<input id="end" type="number" step="1" value="4">
<button id="run" type="button">Extract</button>
<button id="reset" type="button">Reset</button>
<pre id="output" aria-live="polite"></pre>
<script>
const source = document.querySelector('#source');
const start = document.querySelector('#start');
const end = document.querySelector('#end');
const output = document.querySelector('#output');
function show() {
const s = Number(start.value);
const endText = end.value.trim();
const e = endText === '' ? undefined : Number(endText);
if (start.validity.badInput || end.validity.badInput ||
!Number.isInteger(s) || (e !== undefined && !Number.isInteger(e))) {
output.textContent = 'Enter integer indexes. The end may be blank.';
return;
}
const result = e === undefined
? source.value.substring(s)
: source.value.substring(s, e);
output.textContent = `substring() result: ${JSON.stringify(result)}\n` +
`Original: ${JSON.stringify(source.value)}`;
}
document.querySelector('#run').addEventListener('click', show);
document.querySelector('#reset').addEventListener('click', () => {
source.value = '123456789';
start.value = '1';
end.value = '4';
show();
});
show();
</script>
</body>
</html>
Build a preview without splitting visible characters
For a preview limited by UTF-16 (16-bit Unicode Transformation Format) code units, substring() is enough. The DOM example assumes that the page has elements with IDs article-text and preview. Use textContent to read and write plain text. Run the snippet after both elements have been parsed.
const paragraph = document.querySelector('#article-text');
const preview = document.querySelector('#preview');
if (paragraph && preview) {
preview.textContent = paragraph.textContent.substring(0, 40);
}
If the limit counts visible characters, segment the text with Intl.Segmenter and granularity: 'grapheme'. Run the standalone example in a browser supporting that API. See Intl.Segmenter.
{
const text = 'e\u0301🙂z';
const segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
const parts = Array.from(segmenter.segment(text), entry => entry.segment);
const limit = 2;
const preview = parts.slice(0, limit).join('') + (parts.length > limit ? '…' : '');
console.log(text.substring(0, 1)); // 'e'
console.log(preview); // 'é🙂…'
}
The first output is e without the combining accent. The grapheme preview is é🙂…, preserving both clusters and adding an ellipsis because text remains. Preserving whole words requires a separate boundary rule.




