Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 587
magicianiam Avatar asked May 16 '12 19:05

magicianiam


People also ask

How do I check if a string starts with https?

PHP – Check if String Starts with http To check if string starts with “http”, use PHP built-in function strpos(). strpos() takes the string and substring as arguments and returns 0, if the string starts with “http”, else not. This kind of check is useful when you want to verify if given string is an URL or not.

How do I check if a string contains a URL?

HTMLInputElement. checkValidity() method is used to check if a string in <input> element's value attribute is URL . The checkvalidity() method returns true if the value is a proper URL and false if the input is not a proper URL.

How do you check if a regex matches a string?

If you need to know if a string matches a regular expression RegExp , use RegExp.prototype.test() . If you only want the first match found, you might want to use RegExp.prototype.exec() instead.

What is http regex?

A Regular Expression, REGEX, is a special text string for describing a search pattern. Within Hotjar, you can use Regular Expressions to target pages with Feedback widgets or Surveys, or to determine when Hotjar should start recording a user's session.


2 Answers

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
    }
}
like image 163
Ashley Strout Avatar answered Oct 26 '22 07:10

Ashley Strout


Try this:

function validateText(string) {
  if(/(http(s?)):\/\//i.test(string)) {
    // do something here
  }
}
like image 33
Hosein Yeganloo Avatar answered Oct 26 '22 07:10

Hosein Yeganloo