Javascript to trim whitespace when typing a value in a textbox

I am currently trying to show one textbox value in another using javascript function

function fillTextbox() {
            var txtCompanyName = document.getElementById("txtCompanyName").value;
            document.getElementById("txtSecureSite").value = txtCompanyName;
        }

      

and I did it successfully, but now I want to trim the spaces when my user enters a name with spaces. Help as I am new to javascript.

+3


source to share


5 answers


Use string.trim ()

document.getElementById("txtSecureSite").value = txtCompanyName.toString().trim();

      

From MDN



Runs the following code before generating any other String.trim code if not available initially.

if(!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g,'');
  };
}

      

+4


source


You can trim any string value like this:

" string ".trim(); // outputs: "string"

      

Based on: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/Trim



Or use jQuery.trim()

instead:

$.trim(" string "); // outputs: "string"

      

+1


source


var orig = "   foo  ";
alert(orig.trim());

      

In your case:

var txtCompanyName = document.getElementById("txtCompanyName").value;
txtCompanyName  = txtCompanyName.toString().trim();

      

See Trim () in javascript

0


source


Use replace(/(^\s+|\s+$)/g, '')

to remove spaces from the beginning and end of a line.

 function fillTextbox() {
                var txtCompanyName = document.getElementById("txtCompanyName").value;
                var company = txtCompanyName.replace(/(^\s+|\s+$)/g, '');
                document.getElementById("txtSecureSite").value = company;
            }

      

0


source


Try:

function fillTextbox() {
            var txtCompanyName = document.getElementById("txtCompanyName").value;
            var company = txtCompanyName.replace(/\s/g, "");
            document.getElementById("txtSecureSite").value = company;
        }

      

0


source







All Articles