Create a TRIM method for strings

[Total: 0    Average: 0/5]

This script extends JavaScript’s built-in String object by adding a trim() method to it.

Head Code:

<script language="javascript">
// create the prototype on the String object

String.prototype.trim = function() {

 // skip leading and trailing whitespace
 // and return everything in between
  var x=this;
  x=x.replace(/^s*(.*)/, "$1");
  x=x.replace(/(.*?)s*$/, "$1");
  return x;

// copy 'txtIn' to 'txtOut', trimming off unused whitespace
function btnClick() {
  // get the string value from the 'txtIn' element
  var s = document.frm1.txtIn.value;

  // trim the string value and put it into the 'txtOut' element
  document.frm1.txtOut.value = s.trim();


Body Code:

<form name="frm1">
Before: <input type="text" name="txtIn" value="  Example has leading and trailing spaces  " size="50"><br><br>
<input type="button" value="Trim" onclick="javascript:btnClick();"><br><br>
After: <input type="text" name="txtOut" size="50"><br>

Times Viewed: 0

Leave a Reply

Your email address will not be published. Required fields are marked *