19

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

1
  • 1
    fwiw, gskinner.com/RegExr is a great way to learn about regex. Commented May 16, 2012 at 22:22

5 Answers 5

28

Try this:

function validateText(string) {
  if(/(http(s?)):\/\//i.test(string)) {
    // do something here
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

sorry. my bad :)
22

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
    }
}

3 Comments

thanks, let me try this. tried it but it sees every value of tarea as http or https
it empties the value for any input
Yes, that was a logic error on my part as pointed out by @Dan Tao. Fixed now.
5

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)/;

Comments

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

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

1 Comment

Thanks, works fine for me when removing extra ) and adding slashes /((http(s?))\://)/
3

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/

1 Comment

sorry I haven't. i'm partially new to regex and i was not certain what they meant with wordbreak.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.