trim a string from white space by JavaScript function

trackball-K1-48x48 Some times we need to trim a string from white space at the front and end,even all in the string.How can we do that elegantly?Add the following string prototype function to your code. You will call it like predefined String member functions like Substring(),charAt() and indexOf().
The code below shows the function declaration and how to use it.

<SCRIPT LANGUAGE=“JavaScript”>
<!--
//made by minidxer
//For more visit http://ntt.cc
// Trim() , Ltrim() , RTrim()
// trim blank space at the string
String.prototype.Trim = function()
{
return this.replace(/(^\s*)|(\s*$)/g, “”);
}

// trim blank space at the beginning
String.prototype.LTrim = function()
{
return this.replace(/(^\s*)/g, “”);
}

// trim blank space at the end
String.prototype.RTrim = function()
{
return this.replace(/(\s*$)/g, “”);
}
//–>
</SCRIPT>

Sample:

// implementing a trim function for strings in javascript
<script language=“JavaScript” type=“text/javascript”>
var s = new String(” Hello,world!  “);

// use it like this
s=s.trim();
alert(“#” + s + “#”);
// end hiding contents –>
</script>
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • Reddit
  • Technorati
  • StumbleUpon
  • Twitter
RSS Enjoy this Post? Subscribe to Ntt.cc

RSS Feed   RSS Feed     Email Feed  Email Feed Follow us Follow us
You can leave a response, or trackback from your own site.

4 Responses to “trim a string from white space by JavaScript function”

  1. Joules says:

    PS the language attribute for the script tag is deprecated. Also, the script tag should ideally be lowercase to conform with upcoming XHTML standards.

  2. [...] a comment to let me konw that the language attribute for the script tag is deprecated (the article trim a string from white space by JavaScript function ).I wrote another javascript function for trim a string from white space at the front.(It will need [...]

  3. [...] by given separator and returns an array with trimmed  items. It uses the trim() extension at trim a string from white space by JavaScript function or Another JavaScript function for trim a string from white [...]

  4. [...] a previous post trim a string from white space by JavaScript function ( or Another JavaScript function for trim a string from white space ) and JavaScript [...]

Leave a Reply