【问题标题】:jquery replace not replacing all spaces with -jquery替换不替换所有空格 -
【发布时间】:2012-12-16 18:11:43
【问题描述】:

为什么我的 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();
        }
    });

【问题讨论】:

标签: javascript jquery replace


【解决方案1】:

试试这个:

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

演示:JSFiddle

【讨论】:

  • @Norman 您使用的是哪个浏览器? jsFiddle 演示适用于 Firefox 17.0.1。
  • 这在jsfiddle 中工作正常,所以没有错..可能存在一些浏览器兼容性问题..@Norman
  • 我已经更新了你的小提琴。你可以看看吗?我正在使用 Firefox 14.0.1
  • 去哪里看看。?我的答案没有找到任何编辑..@Norman
  • 好的..可能是浏览器问题..我更新了我的答案..@Norman
【解决方案2】:

试试这个:

var str = 'a b c';
var replaced = str.split(' ').join('-');

【讨论】:

    【解决方案3】:

    它是:“if (action.length >= 2 && query.length >= 2 && query.length

    不是:"if (action.length >= 2 && query.length >= 2 && query.lenght

    【讨论】:

      【解决方案4】:

      使用regular expression 替换所有出现的情况:

      query.replace(/\ /g, '-')
      

      【讨论】:

        【解决方案5】:

        你可以试试自定义函数

        String.prototype.replaceAll = function (searchText, replacementText) {
            return this.split(searchText).join(replacementText);
        };
        var text = "This is Sample Text";
        text.replaceAll(" ", "-");
        //final output(This-is-Sample-Text)
        

        【讨论】:

          【解决方案6】:

          试试这个

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

          如果您的查询是undefiniedNaN,这仍然有效

          【讨论】:

            【解决方案7】:

            替换所有空格(包括制表符、空格...):

            query.replace(/\s/g, '_');
            

            【讨论】:

              【解决方案8】:

              String.prototype.replace 仅在其第一个参数是字符串时替换第一个。要替换所有匹配项,您需要传入一个全局正则表达式作为第一个参数。

              replace

              ...

              要执行全局搜索和替换,请在正则表达式中包含 g 开关,或者如果第一个参数是字符串,请在 flags 参数中包含 g。

              其他人展示了许多适用于不同“空间”定义的正则表达式。

              【讨论】:

                猜你喜欢
                • 2018-04-15
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多