how to get domain name from URL string in IE - javascript

I have an AngularJs filter returning the domain name of a given URL string.
app.filter('domain', function() {
return function(input) {
if (input) {
// remove www., add http:// in not existed
input = input.replace(/(www\.)/i, "");
if (!input.match(/(http\:)|(https\:)/i)) {
input = 'http://' + input;
})
var url = new URL(input);
return url.hostname;
}
return '';
};
});
the problem is that because I doesn't support URL() method, it doesn't work in IE.

Yes, according to this document IE doesn't support URL() interface. but let's get out of box! your filter could be written in more short and fast way:
app.filter('domain', function() {
return function(input) {
if (input) {
input = input.replace(/(www\.)/i, "");
if( !input.replace(/(www\.)/i, "") ) {
input = 'http://' + input;
}
var reg = /:\/\/(.[^/]+)/;
return input.match(reg)[1];
}
return '';
};
});

Related

How to replace plus (+) signs with spaces ( ) in GET parameters with javascript

I get users redirected to my site with GET parameters like this:
www.example.com/?email=mail#mail.com&vorname=name1+name2
I use javascript to populate my texfields (newsletter subscription) like this:
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
function getUrlParam(parameter, defaultvalue){
var urlparameter = defaultvalue;
if(window.location.href.indexOf(parameter) > -1){
urlparameter = getUrlVars()[parameter];
}
return urlparameter;
}
var vornametxt = getUrlParam('vorname','');
var emailtxt = getUrlParam('email','');
document.querySelector("input[name=nn]").value = vornametxt;
document.querySelector("input[name=ne]").value = emailtxt;
Like this it works properly but the parameter "vornametxt" contains plus signs if the GET parameter contains them. I want to replace the plus signs in the names with spaces which should work like this:
vornametxt = vornametxt.replace(/\+/g, " ");
That's what I found in older questions on stack overflow but it doesn't work.
What am I doing wrong? Is it possible that my wordpress site doesn't allow certain code?
I am using Wordpress and a plugin which allows me to add this javascript code to my sites footer.
Those values are URI-encoded with + meaning "space". To decode them, replace + with space and then use decodeURIComponent (to handle any other chars that have been encoded). I think it would go in your getUrlParam function, right at the end:
return decodeURIComponent(urlparameter.replace(/\+/g, " "));
Live Example:
(function() {
var window = {
location: {
href: "http://www.example.com/&email=mail#mail.com&vorname=name1+name2"
}
};
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, key, value) {
vars[key] = value;
});
return vars;
}
function getUrlParam(parameter, defaultvalue){
var urlparameter = defaultvalue;
if (window.location.href.indexOf(parameter) > -1) {
urlparameter = getUrlVars()[parameter];
}
return decodeURIComponent(urlparameter.replace(/\+/g, " "));
}
var vornametxt = getUrlParam('vorname','');
var emailtxt = getUrlParam('email','');
document.querySelector("input[name=nn]").value = vornametxt;
document.querySelector("input[name=ne]").value = emailtxt;
})();
<input type="text" name="nn">
<br><input type="text" name="ne">

How to detect a URL from a given string and return that specific URL only - Javascript

I am working on a chrome extension. What i want to accomplish is, when i open a received email, the url from the email text should be detected and an alert box should show which url has been returned from the text. What I have done so far is :
function urlify(text) {
var urlRegex = /(https?:\/\/[^\s]+)/g;
return text.replace(urlRegex, function(url) {
return url;
})
}
var text = document.getElementsByClassName("adn ads")[0].innerText;
var html = urlify(text);
This code detects the URL but, also the returns the rest of the text with it. I just want this function to return me that specified detected url.
A very simple solution I found :
function urlify(text) {
var urlRegex = /(https?:\/\/[^\s]+)/g;
return text.match(urlRegex, function(url) {
return url;
})
}
var text = document.getElementsByClassName("adn ads")[0].innerText;
var html = urlify(text);
console.log(html[0]);
You can use String#match to get a matching url. it returns an array so you can shift off the first value to get the matching value.
function urlify(text) {
return text
.match(/(https?:\/\/[^\s]+)/m)
.shift()
}
var text = 'some text https://stackoverflow.com some more text'
console.log(
urlify(text)
)

URL validate with regular expression and add "http://" when it's missing

I am trying to make a function to validate url regular expression,
and add "http://" if it's missing at the same time.
I am quite new to Javascript and coding, and most part of the below code
is what I have followed a Youtube tutorial.
But I wanted to add a function to prepend "http://" when it's missing,
since with the current regex, both "www.google.com" and "http://www.google.com"
is valid. The problem with this is when I actually click to visit the website,
the ones saved without "http://" at start, doesn't go to the site.
function validateForm(siteName, siteUrl) {
if(!siteName || !siteUrl) {
alert('Please fill in the form');
return false;
}
var expression = /[-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
var result = siteUrl.search(new RegExp(/^http:\/\//i));
if(!siteUrl.match(regex)) {
alert('Please use a valid URL');
return false;
}
else if(siteUrl.match(regex) && !result) {
siteUrl = "http://" + siteUrl
return true;
}
else {
return true;
}
}
You can use the .indexOf() string method to determine if http:// is at the beginning of the string. However, you may run into problems prepending http:// if the URL requires https://.
else if(siteUrl.match(regex) && !result) {
// Check to see if the string starts with "http://"
// indexOf() returns the index position of the supplied
// string argument within the string.
if(siteUrl.indexOf("http://") !== 0){
siteUrl = "http://" + siteUrl
}
return true;
}
Also (as #m_callens points out in the comments below), your siteUrl variable is a function argument, so you won't be able to access it from outside of the function. Instead you should not pass it into the function at all and just have it declared in a higher scope:
var siteUrl = // Code that initializes the variable
function validateForm(siteName) {
if(!siteName || !siteUrl) {
alert('Please fill in the form');
return false;
}
var expression = /[-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
var result = siteUrl.search(new RegExp(/^http:\/\//i));
if(!siteUrl.match(regex)) {
alert('Please use a valid URL');
return false;
}
else if(siteUrl.match(regex) && !result) {
// Check to see if the string starts with "http://"
// indexOf() returns the index position of the supplied
// string argument within the string.
if(siteUrl.indexOf("http://") !== 0){
siteUrl = "http://" + siteUrl
}
}
else {
return true;
}
}

Custom attr() method cannot be given a different name

I have the following perfectly working code (written by someone else). The problem is that if I simply rename the attr method, I get an error. For example, I rename the method to attrx and get this error:
TypeError: arg.attrx is not a function
Here is the working code:
function Action(name) {
this.attr = function(n) {
if (n=="name") {
return "action";
}
},
this.val = function() {
return name;
};
}
Action.prototype.toString = function() {
return "&" + this.attr("name") + "=" + this.val();
}
When a user triggers an event, the following function is called:
function serializeElements() {
var result = "";
for(var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
result += (arg.attr("name") + "=" + arg.val() + "&");
}
return result;
}
Here is the identical code above but it has the attr method renamed to attrx:
function Action(name) {
this.attrx = function(n) {
if (n=="name") {
return "action";
}
},
this.val = function() {
return name;
};
}
Action.prototype.toString = function() {
return "&" + this.attrx("name") + "=" + this.val();
}
function serializeElements() {
var result = "";
for(var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
result += (arg.attrx("name") + "=" + arg.val() + "&");
}
return result;
}
I cannot figure out the reason that the code does not work (see error at top of message) after I rename the method to attrx or anything else for that matter.
Note: The web page does include jQuery, but I don't think that is what causes the problem.
Here is the code used to call serializeElements:
function addStatesListener() {
$("#states").on("change", function(e) {
var form = $(this.form);
var url = form.attr("action");
var type = form.attr("method");
// pass 1) jQuery 'country' and 'state' objects and 2) a query string fragment, e.g.: '&action=change_state'
var data = serializeElements($("#countries"), $("#states"), new Action("change_state"));
e.preventDefault();
$.ajax({
url: url,
type: type,
data: data,
dataType: "html", // The type of data that you're expecting back from the server
success: function(result) {
$("#cities").html(result); // list of all cities, e.g.: <option value="Albany"</option>
}
});
});
}
The proper answer to your question is want already catch #dinesh, you are passing 3 arguments to your function, and only the third is an Action with the .attrx method you changed.
Considering you are working on jquery objects, and if you want to clean your code, you could use .serialize() method instead of calling the couple .attr() and .val().
.serialize() is the jquery method to serialize form objects.
So you can change your code as follow:
function Action(name) {
this.serialize=function() {
return 'name='+encodeURI(name);
}
}
And then your function serializeElements:
function serializeElements() {
var args = Array.prototype.slice.call(arguments);
return args.reduce(function(a, b){
if (a) return a.serialize() + '&' + b.serialize();
if (b) return b.serialize();
});
}
Then you can call it so:
var data = serializeElements($("#countries,#states"), new Action("change_state"));
As you see, you could put form elements in a comma separated list on jquery selector.
That's it.

jQuery redirect to source url

I would like to redirect a user to a target URL on a button click. The target URL is variable and has to be read from the current page URL parameter 'source':
For instance, I have a url http://w/_l/R/C.aspx?source=http://www.google.com
When the user clicks on a button he's being redirect to http://www.google.com
How would I do that with jQuery?
first of all you need to get the url param : source
this can be done with a function like :
function GetParam(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
// you can use it like
var source = GetParam('source');
//then
window.location.href = source
On button click handler, just write window.location.href = http://www.google.com
You will need to parse the query string to get the value of the variable source.
You don't need jQuery for it.
A simple function like this will suffice:
function getFromQueryString(ji) {
hu = window.location.search.substring(1);
gy = hu.split("&");
for (i = 0; i < gy.length; i++) {
ft = gy[i].split("=");
if (ft[0] == ji) {
return ft[1];
}
}
}
location.href = getFromQueryString("source");
Using the url parsing code from here use this to parse your url (this should be included once in your document):
var urlParams = {};
(function () {
var e,
a = /\+/g, // Regex for replacing addition symbol with a space
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
q = window.location.search.substring(1);
while (e = r.exec(q))
urlParams[d(e[1])] = d(e[2]);
})();
Then do this to redirect to the source parameter:
window.location.href = urlParams["source"];
Since you are using the jQuery framework, I'd make use of the jQuery URL Parser plugin, which safely parses and decodes URL parameters, fragment...
You can use it like this:
var source = $.url().param('source');
window.location.href = source;
get url params : (copied from another stackoverflow question) :
var params= {};
document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
function decode(s) {
return decodeURIComponent(s.split("+").join(" "));
}
params[decode(arguments[1])] = decode(arguments[2]);
});
window.location = params['source'];
You can do like this,
<a id="linkId" href=" http://w/_l/R/C.aspx?source=http://www.google.com">Click me</a>
$('#linkId').click(function(e){
var href=$(this).attr('href');
var url=href.substr(href.indexof('?'))
window.location =url;
return false;
});

Categories

Resources