Check if a JavaScript string is a URL
A related question with an answer
Or this Regexp from Devshed:
function validURL(str) {
var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
'((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
'(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
'(\\#[-a-z\\d_]*)?$','i'); // fragment locator
return !!pattern.test(str);
}
JS Regex url validation
I change the function to Match + make a change here with the slashes and its work: (http(s)?://.)
The fixed function:
function isUrlValid(userInput) {
var res = userInput.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g);
if(res == null)
return false;
else
return true;
}
Is there a definitive solution for using jQuery to validate a URL without a plugin?
In short: No, because that's not the purpose of the Jquery library (as @Juhana mentioned).
Also, as @Adeneo wrote, clientside validation is for ui purposes only (i.e. telling the user if it's potentially valid or not). Real validation should be serverside.
That said, I recommend using this regex, which is good for ui purposes.
Validating a URL in Node.js
There's a package called valid-url
var validUrl = require('valid-url');
var url = "http://bla.com"
if (validUrl.isUri(url)){
console.log('Looks like an URI');
}
else {
console.log('Not a URI');
}
Installation:
npm install valid-url --save
If you want a simple REGEX - check this out
Related Topics
Where's the Connection Between Index.HTML and Index.Js in a Create-React-App Application
Pass a JavaScript Variable Value into Input Type Hidden Value
How to Make a Radio Button Unchecked by Clicking It
How to Add "Href" Attribute to a Link Dynamically Using JavaScript
What Is a Text Node, Its Uses? //Document.Createtextnode()
How to Save Canvas Animation as Gif or Webm
HTML Mobile -Forcing the Soft Keyboard to Hide
When Loading an HTML Page via Ajax, Will Script Tags Be Loaded
How to Resize HTML Canvas Element
How to Retain the Scroll Position of a Scrollable Area When Pressing Back Button
Vue 2 - Mutating Props Vue-Warn
Sorting HTML Table with JavaScript
How to Detect the Screen Resolution with JavaScript
Why Is String Concatenation Faster Than Array Join
How to Get the Name of the Currently Running Function in JavaScript