DelphiFAQ Home Search:
General :: Web publishing :: JavaScript :: Strings


This list is sorted by recent document popularity (not total page views).
New documents will first appear at the bottom.

Featured Article

How can I trim a string in JavaScript?


I need to trim a string from white space at the front and end. How can I do that elegantly?


Add the following string prototype function to your code. You will call it like predefined String member functions (such
as indexOf(), charAt() and Substring().

The code below shows the function declaration and how to use it.

This implementation of a trim() function uses two regular expressions to first replace the white space at the begiinning,
then the white space at the end of the string. White space in regular expressions is described as \s.
The beginning of the string is matched by ^ (see the first regex) and the end is matched by $ - in the second regex.

// implementing a trim function for strings in javascript
 <script language="JavaScript" type="text/javascript">
 String.prototype.trim = function () {
     return this.replace(/^\s*/, "").replace(/\s*$/, "");
 var s = new String(" Hello ");
 // use it like this
 alert("!" + s + "!");
 // end hiding contents -->

Generated 8:01:56 on Jan 17, 2017