Validation of URL without www in JavaScript - javascript

Can anyone tell the regular expression for URL validation in JavaScript?
I need to validate for http/https://example.com/...
I tried using
((^http/://[a-zA-Z][0-9a-zA-Z+\\-\\.]*:)?/{0,2}[0-9a-zA-Z;/?:#&=+$\\.\\-_!~*'()%]+)?(#[0-9a-zA-Z;/?:#&=+$\\.\\-_!~*'()%]+)?
The examples that i tried to check were:
http://google.com
https://google.com
www.google.com

You could try something like this:
var url = "Some url...";
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/
if (regexp.test(url)) {
alert("Match");
} else {
alert("No match");
}

Try:
function isUrl(s) {
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)\
(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/
return regexp.test(s);
}
if (isUrl("your_url_here")) {
console.log("URL is valid");
} else {
console.log("URL is invalid");
}
via: http://snippets.dzone.com/posts/show/452

A much more simplified version could be: ^http\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,6}(/\S*)?$
I don't know if this is sufficient for you though, as I don't know what you want to do with the results.

Maybe you could just:
s,(https?://)(?!www\.),\1www.,
and use jquery to validate the transformed string?
It would avoid the job of writing yet another regex to match an URL...

Related

Allow empty string with regex

I'm trying to check if there's a number in a text input using regular expression. Here's the code:
var regex = /^[0-9]+$/;
if (myInput.val().match(regex)) {
console.log("number");
} else {
console.log("bad");
}
It works well, but if I add text, then backspace all the way, I get "bad". How can I make it log "good" when there isn't anything in the text input? I don't want to allow spaces, but I want to allow an empty input.
I tried:
var regex = /\s ^[0-9]+$/;
But then whatever I insert in the input, I always get "bad".
This might fit , either you test for your Exp (^[a-zA-Z0-9]+$) or for an empty string (^$).
var regex = /(^$)|(^[a-zA-Z0-9]+$)/;
if (myInput.val().match(regex)) {
console.log("number");
} else {
console.log("bad");
}
try this (* in place of +)
var regex = /^[0-9]*$/;
if (myInput.val().test(regex)) {
console.log("number");
} else {
console.log("bad");
}

Javascript email regex matching

Please see the Javascript code below. The else if block which is doing a check for email pattern is not allowing any of the email ids . What does the match() function return? Please help.
Used test()
empty field :working fine
wron mail id : working fine
Correct email id : not working
var pattern = new RegExp("/^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/");
if(!accountantEmail){
$("#infoTextMsg").hide();
$("#accountantEmailNoDataErr").show();
$("#accountantEmailInvalidFormat").hide();
$("#accountant_email").focus();
return false;
}
else if(!(pattern.test(accountantEmail))){
$("#accountantEmailInvalidFormat").show();
$("#infoTextMsg").hide();
$("#accountantEmailNoDataErr").hide();
$("#accountant_email").focus();
return false;
}
Javascript match returns an array containing the matches.
Here's the regular expression I use:
var pattern = "[-0-9a-zA-Z.+_]+#[-0-9a-zA-Z.+_]+\.[a-zA-Z]{2,4}";
if(!(accountantEmail.match(pattern))) {
return false;
}
For validation scenarios, you should use the RegExp#test function.
var pattern = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (!pattern.test(accountantEmail)) {
$("#accountantEmailInvalidFormat").show();
$("#infoTextMsg").hide();
$("#accountantEmailNoDataErr").hide();
$("#accountant_email").focus();
return false;
}
As commented on the other posts, the match function is intended for group capturing.
Also note that you were specifying your pattern with an / on it's beginning. This isn't necessary if you're specifying a RegExp as a string.

regex to match date in a string

i try to allow only number 01 (1) to 53) after / and after 2000 and over....
so i create a regex but it don't seem to work
on this web page: http://www.regular-expressions.info/javascriptexample.html
i tried it and it work well... but when i test in on a web page
10/2010 , 23/2000
function isValidDate(value, format){
var isValid = true;
try{
var inputVal = $(this).val();
var dateWWYYYYRegex = '^(0[1-9]|[1234][0-9]|5[0-3])[-/.](20)\d\d$';
var reg=new RegExp(dateWWYYYYRegex);
if(!reg.test(value)){
isValid = false;
alert("Invalid");
}
}
catch(error){
isValid = false;
}
return isValid;
}
You have to escape backslashes if you're going to make a regex from a string. I'd just use regex syntax, since it's a constant anyway:
var reg = /^(0[1-9]|[1234][0-9]|5[0-3])[-/.](20)\d\d$/;
The regular expression doesn't really make any sense, however. It's not clear what it should be, because your description is also confusing.
edit — OK now that I see what you're doing, that regex should work, I guess.
Why use regex for this task? I think it's the wrong tool for this task
Simply split the string by the slash delimiter, and then use numerical functions to check if the values are in the range you want.
function isValidWeekOfYear(value){
var bits = value.split('/');
if(parseInt(bits[1]) < 2000) { return false; } /* probably also want to do a maximum value here? */
if(parseInt(bits[0]) < 1 || parseInt(bits[0]) > 53) { return false; }
return true;
}
It might need a bit more validation than that, but that should be a good starting point for you. Much less processing overhead than a regex just to parse a couple of numbers (and easier to read too).

How to check if the URL contains a given string?

How could I do something like this:
<script type="text/javascript">
$(document).ready(function () {
if(window.location.contains("franky")) // This doesn't work, any suggestions?
{
alert("your url contains the name franky");
}
});
</script>
You need add href property and check indexOf instead of contains
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
if (window.location.href.indexOf("franky") > -1) {
alert("your url contains the name franky");
}
});
</script>
if (window.location.href.indexOf("franky") != -1)
would do it. Alternatively, you could use a regexp:
if (/franky/.test(window.location.href))
You would use indexOf like this:
if(window.location.href.indexOf("franky") != -1){....}
Also notice the addition of href for the string otherwise you would do:
if(window.location.toString().indexOf("franky") != -1){....}
window.location isn't a String, but it has a toString() method. So you can do it like this:
(''+window.location).includes("franky")
or
window.location.toString().includes("franky")
From the old Mozilla docs:
Location objects have a toString
method returning the current URL. You
can also assign a string to
window.location. This means that you
can work with window.location as if it
were a string in most cases.
Sometimes, for example when you need
to call a String method on it, you
have to explicitly call toString.
like so:
<script type="text/javascript">
$(document).ready(function () {
if(window.location.href.indexOf("cart") > -1)
{
alert("your url contains the name franky");
}
});
</script>
The regex way:
var matches = !!location.href.match(/franky/); //a boolean value now
Or in a simple statement you could use:
if (location.href.match(/franky/)) {
I use this to test whether the website is running locally or on a server:
location.href.match(/(192.168|localhost).*:1337/)
This checks whether the href contains either 192.168 or localhost AND is followed by :1337.
As you can see, using regex has its advantages over the other solutions when the condition gets a bit trickier.
document.URL should get you the URL and
if(document.URL.indexOf("searchtext") != -1) {
//found
} else {
//nope
}
Try this, it's shorter and works exactly as window.location.href:
if (document.URL.indexOf("franky") > -1) { ... }
also if you want to check the previous URL:
if (document.referrer.indexOf("franky") > -1) { ... }
Easier it gets
<script type="text/javascript">
$(document).ready(function () {
var url = window.location.href;
if(url.includes('franky')) //includes() method determines whether a string contains specified string.
{
alert("url contains franky");
}
});
</script>
It will be a good practice if you convert your string to lower or uppercase as indexof() method is case sensitive.
This will be if your search isn't case sensitive you can simply use indexOf() method without converting the orignal string to lowercase or uppercase:
var string= location.href;
var convertedString= string.toLowerCase();
if(convertedString.indexOf('franky') != -1)
{
alert("url has franky");
}
else
{
alert("url has no franky");
}
I like this approach, instead.
top.location.pathname.includes('franky')
It works in many cases.
Try this:
<script type="text/javascript">
$(document).ready
(
function ()
{
var regExp = /franky/g;
var testString = "something.com/frankyssssddsdfjsdflk?franky";//Inyour case it would be window.location;
if(regExp.test(testString)) // This doesn't work, any suggestions.
{
alert("your url contains the name franky");
}
}
);
</script>
Try indexOf
if (foo.indexOf("franky") >= 0)
{
...
}
You can also try search (for regular expressions)
if (foo.search("franky") >= 0)
{
...
}
Use Window.location.href to take the url in javascript. it's a
property that will tell you the current URL location of the browser.
Setting the property to something different will redirect the page.
if (window.location.href.indexOf('franky') > -1) {
alert("your url contains the name franky");
}
I like to create a boolean and then use that in a logical if.
//kick unvalidated users to the login page
var onLoginPage = (window.location.href.indexOf("login") > -1);
if (!onLoginPage) {
console.log('redirected to login page');
window.location = "/login";
} else {
console.log('already on the login page');
}
Put in your js file
var url = window.location.href;
console.log(url);
console.log(~url.indexOf("#product-consulation"));
if (~url.indexOf("#product-consulation")) {
console.log('YES');
// $('html, body').animate({
// scrollTop: $('#header').offset().top - 80
// }, 1000);
} else {
console.log('NOPE');
}
Regular Expressions will be more optimal for a lot of people because of word boundaries \b or similar devices. Word boundaries occur when any of 0-9, a-z, A-Z, _ are on that side of the next match, or when an alphanumeric character connects to line or string end or beginning.
if (location.href.match(/(?:\b|_)franky(?:\b|_)))
If you use if(window.location.href.indexOf("sam"), you'll get matches for flotsam and same, among other words. tom would match tomato and tomorrow, without regex.
Making it case-sensitive is as simple as removing the i.
Further, adding other filters is as easy as
if (location.href.match(/(?:\b|_)(?:franky|bob|billy|john|steve)(?:\b|_)/i))
Let's talk about (?:\b|_). RegEx typically defines _ as a word character so it doesn't cause a word boundary. We use this (?:\b|_) to deal with this. To see if it either finds \b or _ on either side of the string.
Other languages may need to use something like
if (location.href.match(/([^\wxxx]|^)(?:franky|bob|billy|john|steve)([^\wxxx]|$)/i))
//where xxx is a character representation (range or literal) of your language's alphanumeric characters.
All of this is easier than saying
var x = location.href // just used to shorten the code
x.indexOf("-sam-") || x.indexOf("-sam.") || x.indexOf(" sam,") || x.indexOf("/sam")...
// and other comparisons to see if the url ends with it
// more for other filters like frank and billy
Other languages' flavors of Regular Expressions support \p{L} but javascript does not, which would make the task of detecting foreign characters much easier. Something like [^\p{L}](filters|in|any|alphabet)[^\p{L}]
a window location is an object that contains multiple methods and props some of them is strings related to URL so you can search for the targeted string safely:
const href = location.href;
// "https://stackoverflow.com/questions/4597050/how-to-check-if-the-url-contains-a-given-string"
// another option
const pathname = location.pathname;
// "/questions/4597050/how-to-check-if-the-url-contains-a-given-string"
// search for string safely
pathname.includes("questions"); // true
href.includes("questions"); // true
The Location Object
Suppose you have this script
<div>
<p id="response"><p>
<script>
var query = document.location.href.substring(document.location.href.indexOf("?") + 1);
var text_input = query.split("&")[0].split("=")[1];
document.getElementById('response').innerHTML=text_input;
</script> </div>
And the url form is www.localhost.com/web_form_response.html?text_input=stack&over=flow
The text written to <p id="response"> will be stack
This is my code ♥
function CheckUrl(url) {
var checkA = url.match(/(https|http):\/\/(.*?)\.(.*?)\.(.*?)(\/|'')/g);
var checkP = url.match(/(https|http):\/\/(.*?)\.(.*?)(\/|'')/g);
if (checkA != null || checkP != null) {
return true;
}
else {
console.log("Error", "The link is not valid");
}
return false;}
You can use javascript string method match
const url = window.location.href;
const find = 'questions';
const found = url.match(find);
console.log(url);
if(found !== null && found[0] === find){
console.log('You are in the questions page');
} else {
console.log('You are not in the questions page');
}

Javascript match part of url, if statement based on result

Here is an example of the url i'm trying to match: http://store.mywebsite.com/folder-1/folder-2/item3423434.aspx
What im trying to match is http: //store.mywebsite.com/folder-1 except that "folder-1" will always be a different value. I can't figure out how to write an if statement for this:
Example (pseudo-code)
if(url contains http://store.mywebsite.com/folder-1)
do this
else if (url contains http://store.mywebsite.com/folder-2)
do something else
etc
In the interest of keeping things very simple...
if(location.pathname.indexOf("folder-1") != -1)
{
//do things for "folder-1"
}
this might give you false positives if the value "folder-1" could be present in other parts of the string. If you are already making sure this is not the case, the provided example should be sufficient.
I would split() the string and check an individual component of the url:
var str = "http://store.mywebsite.com/folder-1/folder-2/item3423434.aspx"
// split the string into an array of parts
var spl = str.split("/");
// spl is now [ http:,,store.mywebsite.com,folder-1,folder-2,item3423434.aspx ]
if (spl[4] == "folder-1") {
// do something
} else if (spl[4] == "folder-2") {
// do something else
}
Using this method it's easy to check other parts of the URL too, without having to use a regular expression with sub-expression captures. e.g. matching the second directory in the path would be if spl[5] == "folder-x".
Of course, you could also use indexOf(), which will return the position of a substring match within a string, but this method is not quite as dynamic and it's not very efficient/easy to read if there are going to be a lot of else conditions:
var str = "http://store.mywebsite.com/folder-1/folder-2/item3423434.aspx"
if (str.indexOf("http://store.mywebsite.com/folder-1") === 0) {
// do something
} else if (str.indexOf("http://store.mywebsite.com/folder-2") === 0) {
// do something
}
Assuming the base URL is fixed and the folder numbers can be very large then this code should work:
var url = 'http://store.mywebsite.com/folder-1/folder-2/item3423434.aspx'
, regex = /^http:..store.mywebsite.com.(folder-\d+)/
, match = url.match(regex);
if (match) {
if (match[1] == 'folder-1') {
// Do this
} else if (match[1] == 'folder-2') {
// Do something else
}
}
Just use URL parting in JS and then you can match URL's against simple string conditions or against regular expressions

Categories