【问题标题】:JQUERY - Trim Function Not WorkingJQUERY - 修剪功能不起作用
【发布时间】:2015-01-10 18:43:58
【问题描述】:

修剪功能无法正常工作

<input class="input"></input>
<div class="button">CLICK</div>



$(".button").click(function() {

    var name = $( ".input" ).val(); 

    name = $.trim(name);

    console.log("TRIM " + name);    
});

http://jsfiddle.net/5sufd9jj/

【问题讨论】:

    标签: jquery input trim


    【解决方案1】:

    Trim 删除字符串开头和结尾的空格。

    如果要删除 连续 个空格,例如 'string string',请使用以下命令:

    $.trim(name.replace(/\s+/g, ' '));
    

    Updated Example

    $(".button").on('click', function() {
        var name = $.trim($('input').val().replace(/\s+/g, ' '));
        console.log("TRIM " + name);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input class="input"></input>
    <div class="button">CLICK</div>

    【讨论】:

      【解决方案2】:

      一切正常。

      trim 函数从提供的字符串的开头和结尾删除所有换行符、空格(包括不间断空格)和制表符。

      它不会从中间删除空格。

      【讨论】:

        【解决方案3】:

        您的输入元素没有任何值,因此返回一个空字符串

        http://jsfiddle.net/lakshay/5sufd9jj/1/

        $(".button").click(function() {
        
        var name = $( ".input" ).val(); 
        
        name = $.trim(name);
        
        $(".input").attr("value",name);\\To show the trimmed sring
        

        });

        【讨论】:

          【解决方案4】:

          String.prototype.trim()

          const greeting = '   Hello world!   ';
          console.log(greeting); // expected output: "   Hello world!   ";
          console.log(greeting.trim()); // expected output: "Hello world!";
          

          Polyfill:

          在任何其他代码之前运行以下代码将创建 trim(),如果它本身不可用。

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2011-01-31
            • 1970-01-01
            • 2013-02-01
            • 1970-01-01
            • 2013-09-13
            • 2020-07-31
            • 2013-10-22
            • 1970-01-01
            相关资源
            最近更新 更多