Remove Extra Spaces in JavaScript with trim()
This Snippet is coded by a user inOnline javascript Compiler. You can see and run this code too.
زبان: JavaScript
trim() removes whitespace from both ends of a string but leaves internal spaces unchanged. To remove extra spaces throughout a string, combine trim() with replace(/\s+/g, ' '): trim() cleans the edges, while the regular expression collapses every run of spaces, tabs, or newlines into a single space.
The example function accepts one string input and returns a cleaned string. It validates the type first, throwing a TypeError for non-string values. Then text.trim() removes leading and trailing whitespace. Finally, replace(/\s+/g, ' ') replaces one or more whitespace characters globally with a single space. For example, ' Hello world ' becomes 'Hello world', and ' JavaScript trim() ' becomes 'JavaScript trim()'.
Time complexity is O(n), where n is the string length: trim() scans the edges and replace() scans the full string. Space complexity is O(n) because JavaScript strings are immutable and a new cleaned string is returned. Use this pattern when normalizing user input, cleaning form fields, or formatting text before display. For English-only edge trimming, trim() alone may be enough; use the regex when internal whitespace also needs normalization.