magicianiam
magicianiam

Reputation: 1579

Regex to check if http or https exists in the string

So i have this code:

function validateText(str)
{
    var tarea = str;
    var tarea_regex = /^(http|https)/;
    if(tarea_regex.test(String(tarea).toLowerCase()) == true)
    {
        $('#textVal').val('');
    }
}

This works perfectly for this:

https://hello.com
http://hello.com

but not for:

this is a website http://hello.com asdasd asdasdas

tried doing some reading but i dont where to place * ? since they will check the expression anywhere on the string according here -> http://www.regular-expressions.info/reference.html

thank you

Upvotes: 19

Views: 57872

Answers (5)

Hosein Yeganloo
Hosein Yeganloo

Reputation: 504

Try this:

function validateText(string) {
  if(/(http(s?)):\/\//i.test(string)) {
    // do something here
  }
}

Upvotes: 28

aztaroth
aztaroth

Reputation: 989

The ^ in the beginning matches the start of the string. Just remove it.

var tarea_regex = /^(http|https)/;

should be

var tarea_regex = /(http|https)/;

Upvotes: 5

Ashley Strout
Ashley Strout

Reputation: 6258

From the looks of it, you're just checking if http or https exists in the string. Regular expressions are a bit overkill for that purpose. Try this simple code using indexOf:

function validateText(str)
{
    var tarea = str;
    if (tarea.indexOf("http://") == 0 || tarea.indexOf("https://") == 0) {
        // do something here
    }
}

Upvotes: 22

web_bod
web_bod

Reputation: 5758

((http(s?))\://))

Plenty of ideas here : http://regexlib.com/Search.aspx?k=URL&AspxAutoDetectCookieSupport=1

Upvotes: 4

Dan Tao
Dan Tao

Reputation: 128327

Have you tried using a word break instead of the start-of-line character?

var tarea_regex = /\b(http|https)/;

It seems to do what I think you want. See here: http://jsfiddle.net/BejGd/

Upvotes: 3

Related Questions