Javascript 在文本框中输入值时修剪空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14892323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 22:51:03  来源:igfitidea点击:

Javascript to Trim spaces when enter value in text box

javascriptasp.net

提问by Asif

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

我目前正在尝试使用 javascript 函数在另一个文本框中显示一个值

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.

我成功地做到了这一点,但现在我想在我的用户输入带空格的名称时修剪空格。请帮忙,因为我是 javascript 新手。

回答by Habib

Use string.trim()

使用string.trim()

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

From MDN

来自MDN

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

如果 String.trim 本机不可用,则在任何其他代码之前运行以下代码将创建 String.trim。

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

回答by Asif

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

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

Or use jQuery.trim()instead:

或者jQuery.trim()改用:

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

回答by Talha

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

In your case:

在你的情况下:

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

See Trim()in javascript

参见javascript 中的Trim()

回答by Pir Abdul

Use replace(/(^\s+|\s+$)/g, '')to remove spaces from the begining and end of the string.

使用replace(/(^\s+|\s+$)/g, '')删除从字符串的开头和结尾空间。

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

回答by Shree

Try :

尝试 :

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