Javascript Trim
Trim is another of Javascript’s useful string manipulation tools. It will remove any ‘whitespace’ from the beginning and end of a string. Whitespace is any character that doesn’t print anything but creates space between other characters. This includes:
- Spaces
- Tabs
- Newlines - which cause text to start appearing on the next line
- Carriable Returns - a relic to typewriter times, still used in Windows in combination with newlines.
Here is an example which contains a few expressions containing trim with comments showing the result of that expression:
var s1 = ' hello ';
console.log(s1.trim()); // 'hello'
var s2 = 'hello ';
console.log(s2.trim()); // 'hello'
// This example uses \ to cause a new line within the string
var s3 = 'hello \
';
console.log(s3.trim()); // 'hello'
JavaScript trim’s cousins: trimStart and trimEnd
The trimStart
and trimEnd
functions are similar to trim
but only trim the start or end of a string.
Here are some examples:
var s1 = ' hello ';
console.log(s1.trimStart()); // 'hello '
var s2 = ' hello ';
console.log(s2.trimEnd()); // ' hello'
You can also use trimLeft
and trimRight
which do the same thing.
Where to use trim
The Javascript trim
function is useful where someone might accidentally paste-in extra spaces that you don’t need. Examples of this are: phone numbers, email addresses and coupon codes.
It’s a bad idea to use trim
on passwords, because the additional space might be on purpose. Web savvy people are used to their passwords needing to be exact and they wouldn’t expect their password to be trimmed by a website.
The Javascript trim
function is useful when parsing text or data. For example if you are parsing a computer program you might use trim to clear up excess whitespace, so that you can concentrate on the symbols or words in the program.
There is a related function called substring if you need more fine-grained control over what you chop out of your string.
Summary
Thanks for reading this quick tutorial on trim
, and good luck with your programming.