Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

regex

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?

like image 855
irl_irl Avatar asked Sep 08 '09 19:09

irl_irl


2 Answers

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;
like image 200
David R Tribble Avatar answered Dec 11 '22 20:12

David R Tribble


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.

like image 37
Adam Bellaire Avatar answered Dec 11 '22 18:12

Adam Bellaire