Peter
Peter

Reputation: 3184

Check if a string starts with http using Javascript

I've been searching all over for an answer to this and all of the answers I've found haven't been in JavaScript.

I need a way, in javascript, to check if a string starts with http, https, or ftp. If it doesn't start with one of those I need to prepend the string with http://. indexOf won't work for me I don't think as I need either http, https or ftp. Also I don't want something like google.com/?q=http://google.com to trigger that as being valid as it doesn't start with an http whereas indexOf would trigger that as being true (if I'm not entirely mistaken).

The closest PHP regex I've found is this:

function addhttp($url) {
   if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
      $url = "http://" . $url;
   }
   return $url;
}

Source: How to add http if its not exists in the url

I just don't know how to convert that to javascript. Any help would be greatly appreciated.

Upvotes: 45

Views: 65047

Answers (8)

ant
ant

Reputation: 21

Using startsWith which is easier to read, just keep in mind that is case-sensitive (hence the conversion of input to lower case)

const startsWithProtocol = (s: string): boolean =>
      ['https://', 'http://', 'ftp://'].some(protocol => s.toLowerCase().startsWith(protocol))

Upvotes: 2

Christoffer
Christoffer

Reputation: 495

Best readability I'd say is to use .startsWith('theString').

The code below checks for both http://, https:// and ftp:// and sets okUrl to a boolean true if any of them comply, by using the || which means or.

When you know if the url contains none of those strings, then just just add http:// to the start of the string either with literals (${})

let url = 'google.com'
const okUrl = url.startsWith('http://') || url.startsWith('https://') || url.startsWith('ftp://')


if (! okUrl) url = `http://${url}`
// => 'http://google.com'

or with simple string concat, which can be done in various ways, for example:

url = 'http://' + url

Read more about it, and test it, here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith

Upvotes: 1

Shota
Shota

Reputation: 7330

Non-Regex declarative way:

const hasValidUrlProtocol = (url = '') => 
    ['http://', 'https://', 'ftp://'].some(protocol => url.startsWith(protocol))

Upvotes: 5

user123444555621
user123444555621

Reputation: 152976

export const getValidUrl = (url = "") => {
    let newUrl = window.decodeURIComponent(url);
    newUrl = newUrl.trim().replace(/\s/g, "");

    if(/^(:\/\/)/.test(newUrl)){
        return `http${newUrl}`;
    }
    if(!/^(f|ht)tps?:\/\//i.test(newUrl)){
        return `http://${newUrl}`;
    }

    return newUrl;
};

Tests:

expect(getValidUrl('https://www.test.com')).toBe('https://www.test.com');
expect(getValidUrl('http://www.test.com')).toBe('http://www.test.com');
expect(getValidUrl('    http   :    /  /  www.test.com')).toBe('http://www.test.com');
expect(getValidUrl('ftp://www.test.com')).toBe('ftp://www.test.com');
expect(getValidUrl('www.test.com')).toBe('http://www.test.com');
expect(getValidUrl('://www.test.com')).toBe('http://www.test.com');
expect(getValidUrl('http%3A%2F%2Fwww.test.com')).toBe('http://www.test.com');
expect(getValidUrl('www    .  test.com')).toBe('http://www.test.com');

Upvotes: 113

Steven Spungin
Steven Spungin

Reputation: 29099

Refining previous answers a bit more, I used new RegExp(...) to avoid messy escapes, and also added an optional s.

var pattern = new RegExp('^(https?|ftp)://');

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

var pattern = new RegExp('^(https?|ftp)://');


console.log(pattern.test('http://foo'));
console.log(pattern.test('https://foo'));
console.log(pattern.test('ftp://foo'));
console.log(pattern.test('bar'));

Upvotes: 3

nicowernli
nicowernli

Reputation: 3348

var url = "http://something.com"
if( url.indexOf("http") == 0 ) {
    alert("yeah!");
} else {
    alert("No no no!");
}

Upvotes: 20

tskuzzy
tskuzzy

Reputation: 36456

This should work:

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

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

jsFiddle

Upvotes: 40

elclanrs
elclanrs

Reputation: 94101

This should work:

var re = /^(http|https|ftp)/

Upvotes: 3

Related Questions