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

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;
}
}

Related

Set body class based on url with params

Im trying to set a body class based on the url - I can get it to work with a plain /Tablet/ url, like the code below.
But I need to set it to a url that has params in it, and I can't get that to work. How do I do it with this url?
/Tablets/?param=grid&pld0page=1&spcs=1
Script:
$(function() {
var loc = window.location.href; // returns the full URL
if(/Tablets/.test(loc)) {
$('body').addClass('test');
}
});
If, as you have mentioned in comments, the query parameter order is important, you can use this...
var url = location.pathname + location.search
console.info(url)
$(document.body).toggleClass('test',
url === '/Tablets/?param=grid&pld0page=1&spcs=1')
This lets you omit the URL scheme, host and port parts, focusing only on the path and query parameters.
You just have to search for text you want in the url string. You are doing fine in the code above. Just change
$(function() {
var loc = window.location.href; // returns the full URL
if(loc.includes('Tablets')) { // will return true/false
$('body').addClass('test');
}
});
Read on includes or here. You can do the same for other tests too, if you are checking for other strings in url. Hope this helps.
You can use this
$(function() {
var url = window.location.href;
url = url.replace(/^.*\/\/[^\/]+/, '')
if(url == '/Tablets?param=grid&pld0page=1&spcs=1') {
$('body').addClass('test');
}
});
If your URL is "http://www.google.com/?param=grid&pld0page=1&spcs=1", then the above queryString variable would be equal to "?param=grid&pld0page=1&spcs=1".
You can check the string is not empty
Replace your code with this
var loc = window.location.href; // returns the full URL
var url = loc.split( '/' );
var chunk = url[ url.length - 2 ];
if(loc.indexOf(chunk) >= 0) {
$('body').addClass('test');
}
var loc = 'http://localhost/Tablets/?param=grid&pld0page=1&spcs=35';
var patt = new RegExp("/Tablets/");
if(patt.test(loc) && loc.split('?').length > 1)
{
console.log('true');
$('body').addClass('test');
}
else
{
console.log('false');
$('body').removeClass('test');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

jQuery.grep() match URL both www and non www, http/https

I am using jquery to search a json string for the matched url and then fetch all the data inside that object.
I fetch the url with
var url = window.location.href;
However this returns
http://somesite.com/
inside the json string could be any of the following
http://somesite.com/
http://somesite.com
http://www.somesite.com/
http://www.somesite.com https://somesite.com/
etc etc.
My code is to match the url and then do something. How would I go about using jQuery.grep() to take the different style urls in the query? Below is my code so far.
var url = window.location.href;
var json = exampleJsonString;
var js = JSON.parse(json);
var result = $.grep(js, function(e){ return e.url == url; });
if (result.length == 0) {
// not found :(
console.log('Not found');
} else if (result.length == 1) {
// Result matched
console.log(result);
}
else {
// multiple items found
console.log('multiple items found');
console.log(result);
}
What I want to do is check for somesite.com using jquery grep. As in this line it checks if the string is equal.
var result = $.grep(js, function(e){ return e.url == url; });
You can use grep function to filter the records. Here in your case want to check different URL's in the object like 'http://somesite.com/','http://somesite.com' etc, mention all the URL's that you want to consider in grep function. Here is the sample code.
var varObj = jQuery.grep(dataobject, function (a) {
if (a.url == "http://somesite.com/" || a.url == "http://somesite.com" || a.url == "http://www.somesite.com/")
return true;
});

how to get domain name from URL string in IE

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 '';
};
});

getParameter - URL parameter with dynamic name values

I've been strugling looking for a way to set a cookie if a URL parameter is persent. The problem is, the name of the URL parameter is half dynamic.
The URL would be:
http://zzzz.test.bbbb/index.html?transaction[XXXX][zzzzz]=YYYYY
Where XXXX and zzzzz are part o the URL name but can change according to what's in the link.
How would the correct getParameterByName function look like in order to recognize the URL parameter transaction[XXXX][zzzzz] ?
I've tried this but it does not work:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp(name + '(?:\\[\\d+\\]?:\\[\\d+\\])?=' + '(.+?)(&|$)'),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
if (getParameterByName("transaction")) {
set_cookie ("Transaction_ID", getParameterByName("transaction"));
}
Any ideas?
Check this JSBIN. This will help you.
Replace locatStr by window.location.search; The below code will work in all scenarios
function getParameterByName(){
var locatStr = '?xyz=123&transaction[XXXX][zzzzz]=YYYYY',
searchStr = locatStr.split('?')[1],
matchArr = searchStr.match(/transaction\[[a-zA-Z0-9]+\]\[[a-zA-Z0-9]+\]/gi),
para;
if(matchArr){
var temp = searchStr.split(matchArr[0]+'=')[1];
return ((temp.indexOf('&')!=-1) ? temp.split('&')[0] : temp);
}
else{
return false;
}
}
var param = getParameterByName();
console.log(param);
if(param){
console.log('set cookie here');
}
else{
console.log('no cookie present');
}
P.S. Dont forget to accept the answer if satisfied

Find out relative urls in javascript

I want to know if the url is relative or no using javascript. Basically i will be passed the url, if the url is relative append the current url i.e minus the file name. Can some one help me with this
eg:-
CURRENT URL = http://example.com/big/index.html
PASSED URL 1 = newindex.html
OUTPUT = http://example.com/big/newindex.html
PASSED URL 2 = http://mysite.com/big/newindex.html
OUTPUT = http://mysite.com/big/newindex.html
So the simplest would be something like
var loc = location.href;
var dir = loc.substring(0,loc.lastIndexOf('/'));
function getHref(urlString) {
if (urlString) return (urlString.toLowerCase().indexOf('http:')==0)?urlString:dir+'/'+((urlString.indexOf('/')==0)?urlString.substring(1):urlString);
}
I am using the location object, substring, indexOflink text, lastIndexOf and the ternary operator - nested
<script type="text/javascript">
var loc = location.href;
var baseurl = loc.substring(0,loc.lastIndexOf('/'));
function getoutputurl(inputurl)
{
var returnurl = '';
if (inputurl)
{
if(inputurl.toLowerCase().indexOf('http://')==0)
{
returnurl = inputurl;
}
else
{
returnurl = baseurl+'/' ;
if(inputurl.indexOf('/')==0)
{
returnurl = returnurl + inputurl.substring(1);
}
else
{
returnurl = returnurl + inputurl;
}
}
}
return returnurl;
}
alert(getoutputurl('http://google.com'));
alert(getoutputurl('google.com'));
</script>
Try out this code it works
Use regular expresion to check if passed url have non relative component. If not create new output url based on part of current url ( cuted via regular exp also for example) and relative part.

Categories

Resources