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.
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.
JavaScript String startsWith()The startsWith() method returns true if a string starts with a specified string. Otherwise it returns false .
You can use the URLConstructor to check if a string is a valid URL. URLConstructor ( new URL(url) ) returns a newly created URL object defined by the URL parameters. A JavaScript TypeError exception is thrown if the given URL is not valid.
To check if a string starts with a substring, call the indexOf() method on the string, passing it the substring as a parameter. If the indexOf method returns 0 , then the string starts with the substring, otherwise it doesn't.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With