How can I remove "http://" from beginning of a URL inside view in an AngularJS app?
I have URLs in database like:
http://example.com/
http://example.com
example.com
but I only need to show
example.com
inside the view.
This deals with HTTP and HTTPS or any other URL. It uses the built-in URL class, which will handle all of the things you haven't thought of correctly.
app.filter('domain', function () {
return function (input) {
try {
var url = new URL(input);
return url.hostname;
} catch (DOMException) {
// Malformed URL. Return original (or something else).
return input; }
};
});
URLs that are correct and you might not have thought of:
http://example.com
http://example.com:8000
http://me#example.com
file://example.com
https://example.com
http://example.com/some-path
http://example.com?some-query-url
You may not need them now, but using the correct library function means your app won't break unexpectedly in future when someone tries to use it for something else.
use this filter in view
app.filter('domain', function () {
return function (input) {
var output = "",
matches;
var urls = /\w+:\/\/([\w|\.]+)/;
matches = urls.exec( input );
if (matches !== null) output = matches[1];
return output;
};
});
Related
While being on a twitter account's page (let's say StackOverflow: https://twitter.com/stackoverflow), I'm trying to get the username of the account, then open a new window querying the account's username on google search. Finally I'd like to get the query text of the newly opened tab.
To do so, I did the following:
function getUserName(callback) {
url = window.location.href;
console.log(url);
sn = url.split("/").slice(-1)[0];
console.log(sn);
window.location.href = `https://google.com/search?q=${sn}`;
callback();
};
function getQuery() {
console.log(window.location.href);
}
getUserName(getQuery);
The problem is that it doesn't wait for the new page to be loaded and thus the console.log() form getQuery() is the twitter's one, instead of the google's.
I know this is a matter of callback and await/async, I've been reading a lot about it but those subjects are confusing me.
Just pass https://google.com/search?q=${sn} into a global variable and use that.
Like this:
let windowHref = window.location.href;
function getUserName(callback) {
url = window.location.href;
console.log(url);
sn = url.split("/").slice(-1)[0];
console.log(sn);
windowHref = `https://google.com/search?q=${sn}`;
window.location.href = windowHref;
callback();
};
function getQuery() {
console.log(windowHref);
}
getUserName(getQuery);
As far as getting the query text of the newly opened tab. You need make use of the callback function within your getUserName() function.
function getUserName(callback) {
url = window.location.href;
console.log(url);
sn = url.split("/").slice(-1)[0];
console.log(sn);
windowHref = `https://google.com/search?q=${sn}`;
callback(windowHref); // Sending back the url to the callback as parameter
};
function getQuery(queryText) { // Value returned from the callback.
console.log(queryText);
}
getUserName(getQuery);
I tried your scenario with linkedin: Sharing the snippets below:
I have a Function (with help of other user of stackoverflow), but only the first if statement works, the second not. I want to take advantage of this code to get both: http and https followed or not by www
function formatURL() {
var url = document.getElementsByName("URL")[0];
var formattedURL = document.getElementsByName("formattedURL")[0];
url = url.value;
if (url.substr(0, 0) === "") // with our without www
{
formattedURL.value = "https://" + url;
return;
} else
{
formattedURL.value = "http://" + url;
return;
}
}
formattedURL.value = url;
}
You're running into this issue because url.substr(0,0) will always be an empty string "" for any string value of url (your if statement is always true).
Not sure what exactly you're trying to compare url.substr against because we don't have all the possible inputs you give to your <URL/> elements. Otherwise, I could have an actual fix for you.
I need to get just the filename without the extension from a url and can't quite get there.
Here's my url in question:
https://www.mealenders.com/shop/index.php/shop/solo-pack.html
Here's what I've tried:
function () {
var value={{Page Path}}.split("/");
return value.reverse()[0];
}
That almost gets me there as it returns "solo-pack.html". What else do I need to do to get rid of the ".html" for this?
Thanks in advance.
You can do the following using javascript. Pop returns the last element which is a string, and then you can use the replace function to get just the filename without .html on the end.
function getFilename () {
return {{ Page Path }}.split('/').pop().replace('.html', '');
}
I see that {{ Page Path }} is probably some templating language but you could modify the above script, to get the current URL and then get the filename as so.
function getFilename () {
return window.location.href.split('/').pop().replace('.html', '');
}
Furthermore you could make it more dynamic to handle any file extension with the following. You need to get the index of the period using indexOf and then sub string from the start of the filename up to the position of the period.
function getFilename () {
var filename = window.location.href.split('/').pop();
return filename.substr(0, filename.lastIndexOf('.');
}
function getFileName(url) {
return url.split("/").pop().split(".")[0];
}
var url = "https://www.mealenders.com/shop/index.php/shop/solo-pack.html";
console.log(getFileName(url));
function () {
var value={{Page Path}}.split("/");
var fileName= value.reverse()[0].split('.')[0];
return fileName;
}
If you need to get rid of any extension, you can use .replace() with regular expression:
var url = "https://www.mealenders.com/shop/index.php/shop/solo-pack.html";
function getFilename (path) {
return path.toString().split('/').pop().replace(/\.\w+$/, '');
}
console.log(getFilename(url));
This will for example change test/index.html into index but index.php.default into index.php and also test.name.with.dots.txt -> test.name.with.dots
Short and sweet:
"https://url/to/file/solo-pack.html".split(/[\\/]/).pop().replace(/\.[^/.]+$/, "")
Returns:
solo-pack
I need to do a URL validation for a CS form. I already have a script there that that checks for http and adds it if not there. However, if I add another function to do just validation, no matter where I put it, it returns URL invalid.
This is what I am running
<script type="text/javascript">
$(function(){
$('.url').blur(function(e) {
if ($(this).val().match(/^http/) || $(this).val().match(/^https/)) /*define the http & https strings */ {
$.noop() /*if strings exist, do nothing */
}
else {
// get value from field
var cur_val = $(this).val();
// do with cur_val
$(this).val('http://' + cur_val);
}
});
});
</script>
This is the second function I used for validation:
<script type="text/javascript">
function validate() {
var url = document.getElementById("url").value;
var pattern = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
if (pattern.test(url)) {
alert("Url is valid");
return true;
}
alert("Url is not valid!");
return false;
}
</script>
What am I doing wrong? I've tried to merge the 2 functions but my js skills choose that exact moment to fail.
Thank you!
I don't know, if this is what you are exactly looking for,
var pattern = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
pattern.test("http://google.com"); // True
pattern.test("google.com"); // False
The if condition you are using is useless, since you return the result of the pattern match anyway.
So the updated Validate function should simply return the pattern results & should look like:
function validate() {
var url = document.getElementById("url").value;
var pattern = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
return pattern.test(url);
}
Assuming that there is a DOM element with id url.
Just from an immediate look, it looks like your "add http" function is looking for tags with class="url", while the validate function is looking for tags with id="url". If you have nothing with that id, then I suppose it would always return invalid.
I have a javascript on my server, and i need to set a value / calling a function inside the javascript when calling a URL. Is there anyway of doing that ?
UPDATE:
<script type="application/x-javascript" src="test-test.js"></script>
Thats how it its loaded on the HTML site. And I want to call the function test(e,e) inside test-test.js, by putting in the URL in a browser with some values for e,e..
Unless you are using one of the few web servers that employs server-side JavaScript, your script is going to run in the browser after the page is loaded. If you want to include information from the URL in your script (and this assumes that you can use a query string without changing the server's behavior), you can use window.location.search to get everything from the question mark onwards.
This function will return either the entire query string (without the question mark) or a semicolon-delimited list of values matching the name value you feed it:
function getUrlQueryString(param) {
var outObj = {};
var qs = window.location.search;
if (qs != "") {
qs = decodeURIComponent(qs.replace(/\?/, ""));
var paramsArray = qs.split("&");
var length = paramsArray.length;
for (var i=0; i<length; ++i) {
var nameValArray = paramsArray[i].split("=");
nameValArray[0] = nameValArray[0].toLowerCase();
if (outObj[nameValArray[0]]) {
outObj[nameValArray[0]] = outObj[nameValArray[0]] + ";" + nameValArray[1];
}
else {
if (nameValArray.length > 1) {
outObj[nameValArray[0]] = nameValArray[1];
}
else {
outObj[nameValArray[0]] = true;
}
}
}
}
var retVal = param ? outObj[param.toLowerCase()] : qs;
return retVal ? retVal : ""
}
So if the URL was, say:
http://www.yoursite.com/somepage.html?name=John%20Doe&occupation=layabout
if you call getUrlQueryString() you would get back name=John Doe&occupation=layabout. If you call getUrlQueryString("name"), you would get back John Doe.
(And yes, I like banner-style indents. So sue me.)
You can use address plugin to be able to pass some condition in urls trough # symbol: http://my_site/my_page#your_condition
in the html you can write something like this:
<script>
$(function(){
// Init and change handlers
$.address.init().change(function(event) {
if (event.value == "your_condition")
run_my_finction();
});
)};
<script>
See this exaple for the futher help.
If you want to execute JavaScript from the browsers' address bar, you can use a self-invoking function:
javascript:(function () {
alert('Hello World');
/* Call the JavaScript functions you require */
})();