Javascript - trim() function

March 2017

Coding in different programming languages demands special attention to be given to strings. In general terms, strings refer to a sequence of characters which are stored using some character encoding. Having leading or trailing spaces in a string can cause critical errors while running a piece of code. Many programming languages provide trim function which can be used to remove these leading or trailing spaces from a string. In JavaScript however, there is no trim function as such. The coder would need to create a custom function in JavaScript by using the replace function to achieve the same results as a regular trim function.

Javascript: the trim() function

The trim() function is native to PHP (and other languages) and is used to remove the spaces at the beginning and end of the string. There is no such function in Javascript, but you can use the following code to get the same results:

Function trim (myString)     
    return myString.replace(/^s+/g,'').replace(/s+$/g,'')     


Published by jad05.
This document, titled "Javascript - trim() function," is available under the Creative Commons license. Any copy, reuse, or modification of the content should be sufficiently credited to CCM (