10

jquery がすべてのスペースを . に置き換えないのはなぜですか'-'。最初のスペースのみを'-'

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

8 に答える 8

34

これで試してください:

.replace(/\s/g,"-");

デモ:JSFiddle

于 2013-01-02T11:13:06.900 に答える
2

「if (action.length >= 2 && query.length >= 2 && query.length <=24) {」です。

ではない: "if (action.length >= 2 && query.length >= 2 && query.length <=24) {"

于 2013-07-17T23:10:48.913 に答える
1

正規表現を使用して、すべてのオカレンスを置き換えます。

query.replace(/\ /g, '-')
于 2013-01-02T11:11:23.057 に答える
0

これを試して

query.replace(/ +(?= )/g,'-');

クエリがundefiniedまたはNaN

于 2013-01-02T11:16:06.540 に答える
0

すべての空白 (タブ、スペースなどを含む) を置き換えます。

query.replace(/\s/g, '_');
于 2013-01-02T11:20:13.890 に答える
0

String.prototype.replace最初の引数が文字列の場合のみ、最初の引数を置き換えます。すべての出現箇所を置き換えるには、最初の引数としてグローバル正規表現を渡す必要があります。

replace

...

グローバルな検索と置換を実行するには、正規表現に g スイッチを含めるか、最初のパラメーターが文字列の場合は、フラグ パラメーターに g を含めます。

他の人は、さまざまな「スペース」の定義で機能する多くの正規表現を示しています。

于 2013-07-17T23:14:29.100 に答える