How to trim whitespace from a string in JavaScript

Trimming whitespace from strings is essential for data validation, form processing, user input cleaning, and ensuring consistent data formatting in JavaScript applications. With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented string trimming extensively in components like form inputs, search fields, and data processors where removing unwanted spaces ensures clean, reliable data handling. From my extensive expertise, the most reliable and built-in solution is using the trim() method, which removes whitespace from both ends of a string. This approach is efficient, universally supported, and specifically designed for cleaning string data.

Use the trim() method to remove leading and trailing whitespace from a string.

const text = '  hello world  '
const cleaned = text.trim()
// Result: 'hello world'

The trim() method removes all whitespace characters (spaces, tabs, newlines) from the beginning and end of a string, returning a new string without modifying the original. In this example, ' hello world '.trim() removes the spaces before ‘hello’ and after ‘world’, resulting in ‘hello world’. The method doesn’t affect whitespace in the middle of the string, only at the edges. It handles various types of whitespace including regular spaces, tabs (\t), and line breaks (\n, \r).

Best Practice Note:

This is the same approach we use in CoreUI components for processing form data, cleaning user input, and ensuring consistent text formatting across our component ecosystem. For removing only leading whitespace, use trimStart() or trimLeft(). For trailing only, use trimEnd() or trimRight(). To remove all whitespace including middle spaces, use text.replace(/\s+/g, ''). The trim() method is supported in all modern browsers and is the standard for string cleaning.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author