Javascript - trim() function

Ask a question
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,'')     
}
Jean-François Pillou

CCM is a leading international tech website. Our content is written in collaboration with IT experts, under the direction of Jeff Pillou, founder of CCM.net. CCM reaches more than 50 million unique visitors per month and is available in 11 languages.

Learn more about the CCM team