惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
V2EX
C
Check Point Blog
博客园 - Franky
月光博客
月光博客
T
Tenable Blog
博客园 - 聂微东
Cyberwarzone
Cyberwarzone
The GitHub Blog
The GitHub Blog
C
CERT Recently Published Vulnerability Notes
Scott Helme
Scott Helme
IT之家
IT之家
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
C
CXSECURITY Database RSS Feed - CXSecurity.com
F
Full Disclosure
博客园 - 司徒正美
Project Zero
Project Zero
Y
Y Combinator Blog
A
Arctic Wolf
美团技术团队
博客园 - 叶小钗
S
Securelist
F
Fortinet All Blogs
T
Threatpost
T
Threat Research - Cisco Blogs
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
酷 壳 – CoolShell
酷 壳 – CoolShell
MyScale Blog
MyScale Blog
大猫的无限游戏
大猫的无限游戏
Recorded Future
Recorded Future
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
S
Schneier on Security
Apple Machine Learning Research
Apple Machine Learning Research
L
LangChain Blog
P
Privacy International News Feed
博客园_首页
S
SegmentFault 最新的问题
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
腾讯CDC
P
Proofpoint News Feed
Cisco Talos Blog
Cisco Talos Blog
AWS News Blog
AWS News Blog
阮一峰的网络日志
阮一峰的网络日志
G
Google Developers Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Simon Willison's Weblog
Simon Willison's Weblog
雷峰网
雷峰网
P
Proofpoint News Feed
Latest news
Latest news
G
GRAHAM CLULEY

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
How to Trim Strings in JavaScript
Dmitri Pavlutin · 2021-11-25 · via Dmitri Pavlutin Blog

A good practice when using string values from form fields is to remove the whitespaces from the start and end of the strings — i.e. trim the string.

In this post, I'm going to describe what is a whitespace and a line terminator character in JavaScript.

Plus, you'll read how to trim strings, aka remove whitespaces and line terminator characters from the start and/or end of the string.

1. The whitespaces and line terminators

Before diving into the actual trim functions, let's first agree what special characters the trim functions are removing from strings.

First, the whitespace is any character from the following list:

  • SPACE (U+0020 code point)
  • CHARACTER TABULATION (U+0009 code point)
  • LINE TABULATION (U+000BU code point)
  • FORM FEED (FF) (U+000C code point)
  • NO-BREAK SPACE (U+00A0 code point)
  • ZERO WIDTH NO-BREAK SPACE (U+FEFFU code point)
  • Any other character from Space Separator category

In simple words, the whitespaces are characters that rendered on the screen create an empty white space.

Common whitespace characters are space ' ' and tab '\t'.

Secondly, the line terminator is also a special set of characters consisting of:

  • LINE FEED (U+000A code point)
  • CARRIAGE RETURN (U+000D code point)
  • LINE SEPARATOR (U+2028 code point)
  • PARAGRAPH SEPARATOR (U+2029 code point)

The line terminator represents a character that exists at the end of a text line and has some special purpose.

A common line terminator character is the line feed '\n', which means moving one line forward.

2. Trim strings in JavaScript

There are situations when you want to clean strings entering from the application input. For example, you'd definitely want to trim strings from the form fields representing a username, first name, last name, phone number, etc.

JavaScript provides 3 simple functions on how to trim strings.

2.1 string.trim()

string.trim() removes sequences of whitespaces and line terminators from both the start and the end of the string.

Let's see a few examples:


const name = ' Kate ';

name.trim(); // => 'Kate'

const phoneNumber = '\t 555-123\n ';

phoneNumber.trim(); // => '555-123'


Open the demo.

name.trim() removes the spaces from the start and end of the string. ' Kate ' becomes 'Kate'.

phoneNumber.trim() also cleans boths ends: '\t 555-123\n ' becomes '555-123'.

The trim function removes from both ends of the string sequences of consecutive white spaces and line terminals. But if a whitespace is found in between two letters, then, of course, this whitespace is preserved:


const fullName = ' Kate Smith ';

fullName.trim(); // => 'Kate Smith'


Open the demo.

fullName.trim() removes the spaces from both the start and end of the string, however keeps the space between Kate and Smith words.

2.2 string.trimStart()

string.trimStart() removes sequences of whitespaces and line terminators only from the start of the string.


const name = ' Jane ';

name.trimStart(); // => 'Jane '

const phoneNumber = '\t 555-123 \n';

phoneNumber.trimStart(); // => '555-123 \n'


Open the demo.

name.trimStart() removes the spaces only from the start of the string, and doesn't touch the space at the end. ' Jane ' becomes 'Jane '.

phoneNumber.trimStart() removes the sequence of whitespaces and line terminals from the start only. '\t 555-123 \n' becomes '555-123 \n'.

2.3 string.trimEnd()

string.trimEnd() removes sequences of whitespaces and line terminators only from the end of the string.


const name = ' Jim ';

name.trimEnd(); // => ' Jim'

const phoneNumber = '\t 555-123 \n';

phoneNumber.trimEnd(); // => '\t 555-123'


Open the demo.

name.trimEnd() removes the one space from the end, and doesn't touch the leading part. ' Jim ' becomes ' Jim'.

phoneNumber.trimEnd() trims the end of the string too. '\t 555-123\n ' becomes '\t 555-123'.

3. Conclusion

The whitespaces, like a space or tab, are special characters that create empty space when rendered.

Also the line terminals, like the line feed, you may find at the end of lines in a multiline string.

Often you may find it useful to remove these special characters from a string. The JavaScript trim functions can help you.

string.trim() removes sequences of white spaces and line terminators from both the start and end of the string, string.trimStart() removes them from start, and finally string.trimEnd() removes them from the end.