在我的 laravel 应用程序中,我处理用户提供的外部 URL。有时用户粘贴时不带 http://
前缀。
UI使用了这个问题的答案:
How to check URL contains http using JQuery and RegEx
我尝试使用这些说明
var lnk = $('#confirmation_URL').val();
var lnk2 = $('#confirmation_URL').val();
//adding http if not present
// if (lnk && !lnk.match(/^.+:\/\/.*/)) { // produces jQuery error
if (lnk && !lnk.match(/^http([s]?):\/\/.*/)) { // produces jQuery error
var lnk = $('http://' + lnk2);
console.log( "prefix http added successfully" );
}
粘贴 URL 时,出现此错误:
jquery-2.1.4.min.js:2 Uncaught Error: Syntax error, unrecognized expression: http://laravel.com/docs/5.1/migrationsga.error @ jquery-2.1.4.min.js:2ga.tokenize @ jquery-2.1.4.min.js:2ga.select @ jquery-2.1.4.min.js:2ga @ jquery-2.1.4.min.js:2n.fn.extend.find @ jquery-2.1.4.min.js:2n.fn.init @ jquery-2.1.4.min.js:2n @ jquery-2.1.4.min.js:2(anonymous function) @ dodaj:1460n.event.dispatch @ jquery-2.1.4.min.js:3r.handle @ jquery-2.1.4.min.js:3
我尝试了什么
jQUery 2.14 和 3.0beta1 的控制台中都会弹出错误
只是为了测试愚蠢的错误并排除潜在原因(例如 jQUery 影响原始变量),我创建了两个具有相同内容的变量:lnk
和 lnk2
。
感谢您的建议。
最佳答案
请尝试这个
$('#confirmation_URL').keyup(function () {
if ( ($(this).val().length >=5) && ($(this).val().substr(0, 5) != 'http:') && ($(this).val().substr(0, 5) != 'https') ) {
$(this).val('http://' + $(this).val());
}
});
关于jquery - 如果不存在,则将 `http://` 添加到字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36686003/