简体   繁体   English

.replace不适用于serializeArray()中的值

[英].replace not working for value in serializeArray()

I am trying to iterate through a form and replace any instance of a space with a + for a certain field. 我试图遍历一个窗体,并用+替换某个字段的任何空格实例。 It seems that I can change the value directly, but I can't get it to replace any instances of a space within that value. 看来我可以直接更改该值,但无法获得它来替换该值内的任何空间实例。

Please see my code below: 请在下面查看我的代码:

$('#search-form').bind('submit', function(){

  var params = new Array();

  $.each($(this).serializeArray(), function(i, field){

       if(field.name == 'submit' || field.name == 'reset') return;

       if(field.name == 'location' && field.value.indexOf(' ')>=0)
       {
            // this is where I am struggling
            this.value.replace(/ /g,"+");
            alert(this.value);
       }                    

       params.push(field.name + '=' + encodeURIComponent(field.value));

  });

  do_search(params.join('&'));

  return false;
});

Any help would be greatly appreciated. 任何帮助将不胜感激。

Thanks 谢谢

*Edit Thanks for the help guys. *编辑感谢您的帮助。 I learned something new about .replace today. 我今天学到了一些有关.replace的新知识。

you need to assign the replacement to the value 您需要将替换项分配给该值

so instead of 所以代替

this.value.replace(/ /g,"+");

change it to 更改为

this.value = this.value.replace(/ /g,"+");

so the whole thing might look like this 所以整个事情看起来像这样

$('#search-form').bind('submit', function(){

  var params = new Array();

  $.each($(this).serializeArray(), function(i, field){

       if(field.name == 'submit' || field.name == 'reset') return;

       if(field.name == 'location' && field.value.indexOf(' ')>=0)
       {
            // this is where I am struggling
            field.value = field.value.replace(/ /g,"+");
       }                    

       params.push(field.name + '=' + encodeURIComponent(field.value));

  });

  do_search(params.join('&'));

  return false;
});

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

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