Ask a question »

Javascript - trim() function

July 2015

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,'')     
}
For unlimited offline reading, you can download this article for free in PDF format:
Javascript-trim-function.pdf

See also

In the same category

Published by jad05. - Latest update by Jeff
This document entitled « Javascript - trim() function » from CCM (ccm.net) is made available under the Creative Commons license. You can copy, modify copies of this page, under the conditions stipulated by the license, as this note appears clearly.