Formatting URL with protocol is required when we binding it to anchor tag.
For example below code anchor tag will redirect to relative path because it doesn't have protocol such as Http, Https etc.,
Below code will check protocol exist or not and add in anchor tag
Below example shows in angularJS
HTML:
For example below code anchor tag will redirect to relative path because it doesn't have protocol such as Http, Https etc.,
Below code will check protocol exist or not and add in anchor tag
function formatHttp(urlPath) {
var urlPattern = new RegExp("^(?:f|ht)tps?://");
if (!urlPattern.test(urlPath)) {
urlPath = "http://" +
urlPath;
}
return urlPath;
}
HTML:
<a ng-href="{{formatHttp(someurl)}}" href="#" target="_blank"> {{someurl}} </a>
someurl is anything like without protocol "www.google.com" or with protocol "http://www.google.com", "https://www.google.com" etc.,
AngularJS Controller:
$scope.formatHttp
= function
(url) {
return formatHttp(url);
};
JS File:
function formatHttp(urlPath) {
var urlPattern = new RegExp("^(?:f|ht)tps?://");
if (!urlPattern.test(urlPath)) {
urlPath = "http://" +
urlPath;
}
return urlPath;
}
No comments:
Post a Comment