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


Articles:

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?

Question:

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

Answer:

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
 s=s.trim();
 alert("!" + s + "!");
 
 // end hiding contents -->
 </script>
 
 

Generated 4:02:16 on Nov 19, 2017