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.
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));
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?
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'];
}
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(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.
Add http://www. in the text if not Exist
You can do like this
String url = textView.getText().toString();
if(!url.startsWith("www.")&& !url.startsWith("http://")){
url = "www."+url;
}
if(!url.startsWith("http://")){
url = "http://"+url;
}
You can use this url to display content in WebView
Hope this will solve your problem
Add http:// to NSURL if it's not there
NSString *urlString = @"google.com";
NSURL *webpageUrl;
if ([urlString hasPrefix:@"http://"] || [urlString hasPrefix:@"https://"]) {
webpageUrl = [NSURL URLWithString:urlString];
} else {
webpageUrl = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@", urlString]];
}
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:webpageUrl];
[self.myWebView loadRequest:urlRequest];
Related Topics
How to Call a PHP Function on the Click of a Button
Deny Direct Access to a Folder and File by Htaccess
How to Check If Mod_Rewrite Is Enabled in PHP
"Cannot Send Session Cache Limiter - Headers Already Sent"
How to Get Protected Property of Object in PHP
Using PHP 5.5'S Password_Hash and Password_Verify Function
Correct Way to Use Like '%{$Var}%' With Prepared Statements
Print String With a PHP Variable in It
PHP Code to Convert a MySQL Query to Csv
Selecting a CSS Class With Xpath
PHP Sort Array by Subarray Value
How to Execute Two MySQL Queries as One in PHP/MySQL
Get First Key in a (Possibly) Associative Array
How to Make an Asynchronous Get Request in PHP