jquery替换不替换所有空格 -

Nor*_*man 9 javascript jquery replace

为什么我的jquery没有用a替换所有空格'-'.它只用一个替换第一个空格'-'

$('.modhForm').submit(function(event) {

        var $this = $(this),
            action = $this.attr('action'),
            query = $this.find('.topsearchbar').val(); // Use val() instead of attr('value').

        if (action.length >= 2 && query.length >= 2 && query.lenght <=24) {

          // Use URI encoding
          var newAction = (action + '/' + query.replace(' ','-'));
          console.log('OK', newAction); // DEBUG

          // Change action attribute
          $this.attr('action', newAction);

        } else {
          console.log('To small to be any good'); // DEBUG

          // Do not submit the form
          event.preventDefault();
        }
    });
Run Code Online (Sandbox Code Playgroud)

Vis*_*har 30

试试这个:

.replace(/\s/g,"-");
Run Code Online (Sandbox Code Playgroud)

演示:JSFiddle