Home Java Javascript - trim() function

Javascript - trim() function

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 myStringeplace(/^s+/geplace(/s+$/g,'') }

  • Java

LEAVE A REPLY

Please enter your comment!
Please enter your name!