irl_irl
irl_irl

Reputation: 3975

How to check if a string contains http:// at the start

I want to be able to check a string to see if it has http:// at the start and if not to add it.

if (regex expression){
string = "http://"+string;
}

Does anyone know the regex expression to use?

Upvotes: 6

Views: 30049

Answers (9)

Kyle Coots
Kyle Coots

Reputation: 2131

For me, with PHP these are the 2 I use just adding them here for completeness.

$__regex_url_no_http = "@[-a-zA-Z0-9\@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()\@:%_\+.~#?&//=]*)@";

$__regex_url_http = "@https?:\/\/(www\.)?[-a-zA-Z0-9\@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()\@:%_\+.~#?&//=]*)@";

I have a function like this to check:

/**
 * Filters a url @param url If @param protocol is true
 * then it will check if the url contains the protocol
 * portion in the url if it doesn't then false will be
 * returned.
 * 
 * @param string $url
 * @param boolean $protocol
 * @return boolean
 */   
public function filter_url($url, $protocol=false){
  $response = FALSE;

  $regex = $protocol == false ? $this->__regex_url_no_http:$this->__regex_url_http;

  if(preg_match($regex, $url)){
    $response = TRUE;
  }

  return $response;
}

I didn't create the regex. I found them someplace but seem to be compliant

Upvotes: 0

David R Tribble
David R Tribble

Reputation: 12204

If you don't need a regex to do this (depending on what language you're using), you could simply look at the initial characters of your string. For example:

// C#
if (!str.StartsWith("http://"))
    str = "http://" + str;

// Java
if (!str.startsWith("http://"))
    str = "http://" + str;

// JavaScript/TypeScript
if (str.substring(0, 7) !== 'http://')
    str = 'http://' + str;

Upvotes: 58

Deepti Gehlot
Deepti Gehlot

Reputation: 617

var url = "http://abcd";
var pattern = /^((http|https|ftp):\/\/)/;

if(!pattern.test(url)) {
    url = "http://" + url;
}

alert(url);

Upvotes: 6

Michael Ciba
Michael Ciba

Reputation: 561

Something like this should work ^(https?://)

Upvotes: 3

Nicolas Dorier
Nicolas Dorier

Reputation: 7465

yourString = yourString.StartWith("http://") ? yourString : "http://" + yourString

Is more sexy

Upvotes: 2

vsync
vsync

Reputation: 130165

If javascript is the language needed here, then look at this post which adds "startswith" property to the string type.

Upvotes: 0

Adam Bellaire
Adam Bellaire

Reputation: 110489

Should be:

/^http:\/\//

And remember to use this with ! or not (you didn't say which programming language), since you are looking for items which don't match.

Upvotes: 8

Chris Doggett
Chris Doggett

Reputation: 20757

In JavaScript:

if(!(/^http:\/\//.test(url)))
{
    string = "http://" + string;
}

Upvotes: 7

scragar
scragar

Reputation: 6824

 /^http:\/\//

Upvotes: 1

Related Questions