用于从.value中删除空格的Javascript

时间:2016-11-17 07:34:43

标签: javascript jquery trim

//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) == ""),但它不能删除内联空格并仅删除前导和尾随空格。

5 个答案:

答案 0 :(得分:2)

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

请注意,trim在IE中可能不是免费的。 9版。所以你可以使用:

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

答案 1 :(得分:2)

$.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());
          }
       });
    }
 });

答案 2 :(得分:1)

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

var val = this.value.trim();

答案 3 :(得分:0)

试试这个:

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

答案 4 :(得分:0)

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

.replace(/ \ S / G,'&#39)