编辑:明确一点,我的问题是:如果输入的值已经是一个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/

最佳答案

因此,可以肯定的是,我将您的要求读为:


在粘贴到输入中
如果现有值是url并且粘贴的值是url
将现有网址替换为粘贴的网址


如果是这样,下面的操作将在粘贴时连续执行:

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

09-10 11:18
查看更多