替换URL正则表达式

Replace URL Regex

本文关键字:正则表达式 URL 替换      更新时间:2023-09-26

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

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

如果user copy string中有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. 如果现有值为url且粘贴值为url
  2. 将现有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示例