繁体   English   中英

Javascript从.value中删除空格

[英]Javascript to remove spaces from .value

//loop thought all the sku field
$('.optionSku').each(function() {

    //if found field are empty
    if (jQuery.trim(this.value) == "") {

        //loop thought all the name field to copy to the empty field
        $('.optionName').each(function() {

            if ($(this).closest("tr").find(".optionSku").val() == "") {

                empty++;
                $(this).closest("tr").find(".optionSku").val($(this).val());
            }

        });
    }
})

如何使用 JQuery 从 this.value 中删除空间? 我尝试放置if (jQuery.trim(this.value) == "") ,但它无法删除内联空格并且仅删除前导和尾随空格。

this.value =  this.value.trim(); 
//you need to assign the trimmed value back to it.

请注意,在 IE < 9 版本中, trim可能不可用。 所以你可以使用:

this.value = $.trim(this.value);

$.trim()函数从提供的字符串的开头和结尾删除所有换行符、空格(包括不间断空格)和制表符。 如果这些空白字符出现在字符串的中间,它们将被保留。
如果要删除前导和尾随空格,请使用

//loop thought all the sku field
 $('.optionSku').each(function() {
    //if found field are empty
    if ($.trim(this.value)=="") {
       //loop thought all the name field to copy to the empty field
       $('.optionName').each(function() {
          if ($(this).closest("tr").find(".optionSku").val() == "") {
             empty++;
             $(this).closest("tr").find(".optionSku").val($(this).val());
          }
       });
    }
 });

如果你想内联空格使用

//loop thought all the sku field
 $('.optionSku').each(function() {
    //if found field are empty
    if (this.value.trim()=="") {
       //loop thought all the name field to copy to the empty field
       $('.optionName').each(function() {
          if ($(this).closest("tr").find(".optionSku").val() == "") {
             empty++;
             $(this).closest("tr").find(".optionSku").val($(this).val());
          }
       });
    }
 });

这就是修剪在 javascript 中的工作方式。

var val = this.value.trim();

试试这个:

if(this.value.trim()==""){
    //code here
}

.replace(//g,'') g 字符表示在整个字符串中重复搜索。 如果您想匹配所有空格,而不仅仅是文字空格字符,也可以使用 \\s:

.replace(/\\s/g,'')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM