Trim a string with regex in JavaScript
Beginner · 3 min read
When people type into a form, extra spaces sneak in. Someone copies their name with a space on the end, or a phone keyboard adds one after a word. Then 'Lagos ' doesn't equal 'Lagos', and a search or a login fails for no visible reason. Trimming removes the whitespace from the two ends of a string and leaves the inside alone.
JavaScript has a built-in trim(), and in real code you should use it. Writing your own with a regular expression is still worth doing once, because it teaches four pattern ideas in one short line: \s, +, anchors and |. You need to know what a string and a function are.
Whitespace and \s
Whitespace means characters you can't see: the ordinary space, a tab, a new line. In a pattern, \s matches any one of them. + after it means "one or more in a row":
console.log(/\s+/.test('Lagos to Abuja')); // true: there are spaces
console.log(/\s+/.test('Lagos')); // false
Replacing with nothing
replace(pattern, '') finds what the pattern matches and swaps it for an empty string, which removes it:
console.log('a-b'.replace(/-/, '')); // 'ab'
So trimming is just: find the whitespace at the ends, replace it with nothing.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
5 A trim function built from a regex
easyRemove whitespace from both ends of a string with a regular expression, and provide left-only and right-only versions.
Stuck? Three hints, smallest first
- 1.
/^\s+|\s+$/greplaced with nothing does both ends at once. - 2.
\scovers tabs, newlines and a non-breaking space, not only the plain space. - 3. Anchor both ends, or you strip the spaces inside the string too.
Step 1: trim the start
^ anchors the pattern to the very start. ^\s+ means "one or more whitespace characters at the start":
const trimStart = (text) => text.replace(/^\s+/, '');
console.log(JSON.stringify(trimStart(' Lagos to Abuja '))); // "Lagos to Abuja "
JSON.stringify puts quotes around the result so you can see the spaces that are left at the end.
Step 2: trim the end
$ anchors to the very end. \s+$ is "one or more whitespace characters at the end":
const trimEnd = (text) => text.replace(/\s+$/, '');
console.log(JSON.stringify(trimEnd(' Lagos to Abuja '))); // " Lagos to Abuja"
Step 3: both ends at once
| means "or". ^\s+|\s+$ matches whitespace at the start or whitespace at the end. Try it:
const almost = (text) => text.replace(/^\s+|\s+$/, '');
console.log(JSON.stringify(almost(' Lagos to Abuja '))); // "Lagos to Abuja "
Only the start went. Without the g flag, replace stops after the first match. Add g and it keeps going:
const trim = (text) => text.replace(/^\s+|\s+$/g, '');
console.log(JSON.stringify(trim(' Lagos to Abuja '))); // "Lagos to Abuja"
console.log(trim(' Lagos to Abuja ') === ' Lagos to Abuja '.trim()); // true
It gives the same result as the built-in trim().
Step 4: the bug of no anchors
The mistake this exercise exists to show is dropping the anchors:
const broken = (text) => text.replace(/\s+/g, '');
console.log(broken(' Lagos to Abuja ')); // 'LagostoAbuja'
Without ^ and $, the pattern matches every run of whitespace, so the spaces between the words disappear too. This bug looks fine on one-word test data and only shows up on real input.
Step 5: what counts as whitespace
\s is wider than the space bar. Tabs (\t), new lines (\n), carriage returns (\r) and the non-breaking space (\u00a0) all count:
const trim = (text) => text.replace(/^\s+|\s+$/g, '');
console.log(trim('\t\n Ojota \u00a0\r\n')); // 'Ojota'
console.log(trim('\u200bLagos').length); // 6
The second line is the surprise. \u200b is a zero-width space, an invisible character that often comes along with copied text. It is not in \s, so it survives, and the string is 6 characters long even though you only see five letters.
The full solution
The panel has all three functions, the broken one for comparison, and a string mixing tabs, new lines and a non-breaking space. Press Run and compare each result with the built-in methods.
const trim = (text) => text.replace(/^\s+|\s+$/g, '');
const trimStart = (text) => text.replace(/^\s+/, '');
const trimEnd = (text) => text.replace(/\s+$/, '');
// The mistake this exercise exists to show: no anchors.
const broken = (text) => text.replace(/\s+/g, '');
const messy = ' Lagos to Abuja ';
const mixed = '\t\n Ojota \u00a0\r\n';
console.log('input :', JSON.stringify(messy));
console.log('trim :', JSON.stringify(trim(messy)));
console.log('trimStart :', JSON.stringify(trimStart(messy)));
console.log('trimEnd :', JSON.stringify(trimEnd(messy)));
console.log('no anchors :', JSON.stringify(broken(messy)), '<- ate the inner spaces too');
console.log('tabs, newlines and a non-breaking space:', JSON.stringify(trim(mixed)));
console.log('built-in agrees:', trim(messy) === messy.trim());
Output
14 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 14 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('both ends are trimmed', trim(messy), 'Lagos to Abuja');
test('it agrees with the built-in trim', trim(messy), messy.trim());
test('the inner space survives', trim(messy).includes(' '), true);
test('the unanchored version destroys it', broken(messy), 'LagostoAbuja');
test('trimStart leaves the end alone', JSON.stringify(trimStart(messy)), JSON.stringify('Lagos to Abuja '));
test('trimEnd leaves the start alone', JSON.stringify(trimEnd(messy)), JSON.stringify(' Lagos to Abuja'));
test('they agree with the built-ins', [trimStart(messy) === messy.trimStart(), trimEnd(messy) === messy.trimEnd()], [true, true]);
test('a string with nothing to trim is unchanged', trim('Lagos'), 'Lagos');
test('a string of only spaces becomes empty', trim(' '), '');
test('an empty string stays empty', trim(''), '');
test('tabs and newlines are whitespace', trim('\t\nLagos\n\t'), 'Lagos');
test('and a non-breaking space is too', trim('\u00a0Lagos\u00a0'), 'Lagos');
test('but a zero-width space is NOT', trim('\u200bLagos'), '\u200bLagos');
test('so it survives the trim', trim('\u200bLagos').length, 6);
/^s+|s+$/g is the whole answer: the alternation matches either end, and the g flag lets it do both in one pass. Without the anchors you get /s+/g, which removes every run of whitespace — the assertion shows ' Lagos to Abuja ' becoming 'LagostoAbuja'. That is a real bug people ship.
s is broader than a space: tabs, newlines, carriage returns, form feeds and the non-breaking space all count, and the assertions check them. The one that catches people is the zero-width space , which is not in s and so survives — it is invisible, it arrives constantly from copy-pasted text, and it makes two apparently identical strings unequal.
In practice use String.prototype.trim, which is faster and clearer. The regex is worth writing once to understand what it is doing.
Common mistakes
- Leaving out
^and$. That removes every space, including the ones between words. - Forgetting the
gflag on the combined pattern. Only the first end gets trimmed. - Assuming trimmed text is clean. A zero-width space can still be hiding at the start. If matches fail on text that looks identical, check its
length.
Try it yourself
- Write
squash(text)that trims the ends and turns every run of inner spaces into one space. (Hint: trim first, thenreplace(/\s+/g, ' ').) - Write
trimDashes(text)that removes dashes from both ends:'--route--'becomes'route'. - Extend
trimto also remove\u200b. (Hint:[\s\u200b]is a class with both.)