替换URL Regex

时间:2014-05-27 12:37:51

标签: javascript regex

编辑:为了清楚起见,我的问题是:如果输入已经有一个url作为其值,如何用第一个url替换第一个url?

如果用户粘贴包含url的字符串(必须以url开头),我想替换url字符串。在文档加载时,输入的值已经是url。例如:http://www.stackoverflow.com/questions

如果用户复制字符串中包含url,请从输入中替换第一个url字符串。

例如:https://stackoverflow.com/questions/ask

我们将使用用户粘贴替换第一个。

我使用下面的代码完成了这项工作,但也没有像我想的那样工作。

$(document).on('paste', 'input.link', function(){
    var $element = $(this);
    setTimeout(function(){
        var $val = $element.val();
        var $exp = /(https?:\/\/(?:w{3}\.)?stackoverflow\.com\/?)+/g;

        if($val.match($exp)){
            var $count = 0;

            $val = $val.replace($exp, function(match) {
                $count++;

                if($count > 1) {
                    return match;
                } else {
                    return '';
                }
            });

            $element.val($val);
        }
    }, 100);
});

测试:http://jsfiddle.net/Lt9zn/

1 个答案:

答案 0 :(得分:1)

所以,当然,我将您的要求视为:

  1. 粘贴到输入
  2. 如果现有值为url且粘贴值为url
  3. 用粘贴的网址替换现有网址
  4. 如果是这样,以下将继续粘贴:

    function escape(str) {
      return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
    }
    
    var url_match = /(https?:\/\/)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&\/=]*)/;
    
    $('input').on('paste', function() {
        if (url_match.test($(this).val())) {
            var current_value = $(this).val(),
                match_current = new RegExp('^('+escape(current_value)+')(.*)$');
            setTimeout(function() {
                var matches = $('input').val().match(match_current);
                if (matches && matches.length >= 3 && url_match.test(matches[2])) {
                    $('input').val(matches[2]);
                }
            },100);
        }
    });
    

    查看工作JSFiddle Example

相关问题