tags:

views:

434

answers:

7

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?

+1  A: 
 /^http:\/\//
scragar
+4  A: 

In JavaScript:

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

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.

Adam Bellaire
+1  A: 

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

Michael Ciba
You need to escape the /s.
scragar
+10  A: 

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:

if (!string.StartsWith("http://"))
    string = "http://" + string;
//or//
if (string.Substring(0, 7) != "http://")
    string = "http://" + string;`
Loadmaster
May many, many upvotes be bestowed upon you. Sometimes, regexes are overkill.
Samir Talwar
Thank you for the blessing. Yes, sometimes powerful language features are overused. Regex's are not as fast as simple string operations.
Loadmaster
A: 

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

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

Is more sexy

Nicolas Dorier