Search code examples
jqueryregexlaravellaravel-5prefix

jquery - adding `http://` to string if not present


In my laravel app I process an external URL provided by user. Sometimes user would paste it without the http:// prefix. UI have used this question's answers: How to check URL contains http using JQuery and RegEx

I tried to use these instructions

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" );
}

When pasting an URL, I get this error:

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

what i tried

The error pops out in console for both jQUery 2.14 and 3.0beta1 Just to test for silly mistakes and exclude potential causes (such as jQUery affecting the original variable) , I created two variables with identical content: lnk and lnk2.

Thank you for your suggestions.


Solution

  • Please try this

    $('#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());
            }
        });