Add http(s) to URL if it's not there?
Use a before filter to add it if it is not there:
before_validation :smart_add_url_protocol
protected
def smart_add_url_protocol
unless url[/\Ahttp:\/\//] || url[/\Ahttps:\/\//]
self.url = "http://#{url}"
end
end
Leave the validation you have in, that way if they make a typo they can correct the protocol.
How to add http:// if it doesn't exist in the URL
A modified version of @nickf code:
function addhttp($url) {
if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
$url = "http://" . $url;
}
return $url;
}
Recognizes ftp://
, ftps://
, http://
and https://
in a case insensitive way.
Prepending http:// to a URL that doesn't already contain http://
A simple solution for what you want is the following:
var prefix = 'http://';
if (s.substr(0, prefix.length) !== prefix)
{
s = prefix + s;
}
However there are a few things you should be aware of...
The test here is case-sensitive. This means that if the string is initially Http://example.com
this will change it to http://Http://example.com
which is probably not what you want. You probably should also not modify any string starting with foo://
otherwise you could end up with something like http://https://example.com
.
On the other hand if you receive an input such as example.com?redirect=http://othersite.com
then you probably do want to prepend http://
so just searching for ://
might not be good enough for a general solution.
Alternative approaches
Using a regular expression:
if (!s.match(/^[a-zA-Z]+:\/\//))
{
s = 'http://' + s;
}Using a URI parsing library such as JS-URI.
if (new URI(s).scheme === null)
{
s = 'http://' + s;
}
Related questions
- Javascript equalsIgnoreCase: case insensitive string comparation
- javascript startswith
- How do I parse a URL into hostname and path in javascript?
How can I add http:// to a URL if no protocol is defined in JavaScript?
Use the same function in JavaScript:
function addhttp(url) {
if (!/^(?:f|ht)tps?\:\/\//.test(url)) {
url = "http://" + url;
}
return url;
}
How to add http:// if it doesn't exist in a string containing multiple URLs
Use the g
modifier. Without it, your regexp will only find the first match.
Also, String.replace()
doesn't return a Promise. You don't need await
.
const str = ` Unroll the pastry on to a lightly floured work surface. Cut is [Google](www.google.com/)
into 2 long rectangles. Cut the large rectangle in half lengthways, then cut both smaller reckk
Bake in the oven for 25–30 minutes, or until the pastry has turned golden-brown and looks crisp.
Remove from the oven and leave to cool slightly before serving. Unroll the pastry on to a lightly floured work surface.
this is my [web](www.stackoverflow.com), this is [Google](https://www.google.com/)
Cut into 2 long rectangles. Cut the large rectangle in half lengthways, then cut both smaller rectangles into eight equal sections. You now have 16 rectangles in total.
Brush one end of each rectangle with a little of the beaten egg`;
function urlify(text) {
var urlRegex = new RegExp(
'([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?',
'g'
);
return text.replace(urlRegex, (url) => {
if (url.search(/^http[s]?\:\/\//) === -1) {
return 'http://' + url;
} else {
return url;
}
});
}
console.log(urlify(str));
How can I prepend http to a url if it doesn't begin with http?
Python do have builtin functions to treat that correctly, like
p = urlparse.urlparse(my_url, 'http')
netloc = p.netloc or p.path
path = p.path if p.netloc else ''
if not netloc.startswith('www.'):
netloc = 'www.' + netloc
p = urlparse.ParseResult('http', netloc, path, *p[3:])
print(p.geturl())
If you want to remove (or add) the www
part, you have to edit the .netloc
field of the resulting object before calling .geturl()
.
Because ParseResult
is a namedtuple, you cannot edit it in-place, but have to create a new object.
PS:
For Python3, it should be urllib.parse.urlparse
Add http:// prefix to URL when missing
A simple solution which may not work in all cases (i.e. 'https://'):
if (strpos($aProfileInfo['Website'],'http://') === false){
$aProfileInfo['Website'] = 'http://'.$aProfileInfo['Website'];
}
having https at the beginning of URL without having to manually add it
You can easily redirect to the https version of any page using rewrite rules/rewrite module of your web server (the exact way to do this depends on the webserver used). Ask your provider, this is a common case so there may even be a UI option in your console to do this.
Regarding google see this: https://webmasters.stackexchange.com/questions/67212/how-to-convince-google-to-list-https-version-of-website
It may also be good form to verify the protocol used to access the site in your authentication module and refuse authentication if the wrong protocol is used. Assuming web rules are used to redirect traffic this would to prevent leaking information due to a misconfiguration/bug.
Related Topics
"Whenever" Gem Running Cron Jobs on Heroku
How to Change All the Keys of a Hash by a New Set of Given Keys
Comparing Two Arrays Ignoring Element Order in Ruby
Warning: Can't Verify Csrf Token Authenticity in Case of API Development
How to Serve Requests Concurrently with Rails 4
Can Rails Migrations Be Used to Convert Data
How to Get the Class of a Basicobject Instance
Rails Forms for Has_Many Through Association with Additional Attributes
Dividing Elements of a Ruby Array into an Exact Number of (Nearly) Equal-Sized Sub-Arrays
Add Method to an Instanced Object
Getting an Ascii Character Code in Ruby Using '' (Question Mark) Fails
How to Unzip a File in Ruby on Rails
Using Implicit 'Subject' with 'Expect' in Rspec-2.11
Rails with Ruby-Debugger Throw 'Symbol Not Found: _Ruby_Current_Thread (Loaderror)'