Skip to content
Advertisement

Javascript to Trim spaces when enter value in text box

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

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

and i successfully done this but now i want to trim spaces when my user enters a name with spaces. Please help as i am new in javascript.

Advertisement

Answer

Use string.trim()

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

From MDN

Running the following code before any other code will create String.trim if it’s not natively available.

if(!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^s+|s+$/g,'');
  };
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement