Check If a JavaScript String Is a Url

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

How to detect whether a string is in URL format using javascript?

Try this-

function isUrl(s) {
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
return regexp.test(s);
}

usage: if (isUrl("http://www.page.com")) alert("is correct") else
alert("not correct");

How to check if the URL contains a given string?

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>

How to check if http is in the string?

You can use the URL webApi.

https://developer.mozilla.org/en-US/docs/Web/API/URL/URL

If the string passed to the constructor is not a valid URL format, it will throw an error that you can catch.

How to check if url scheme is present in a url string javascript

You can do it quite easily with a little bit of regex. The pattern /^[a-z0-9]+:\/\// will be able to extract it.

If you just want to test if it has it, use pattern.test() to get a boolean:

/^[a-z0-9]+:\/\//.test(url); // true

If you want what it is, use url.match() and wrap the protocol portion in parentheses:

url.match(/^([a-z0-9]+):\/\//)[1] // https

Here is a runnable example with a few example URLs.

const urls = ['file://test.com', 'http://test.com', 'https://test.com', 'example.com?http'];
console.log( urls.map(url => (url.match(/^([a-z0-9]+):\/\//) || [])[1]));


Related Topics



Leave a reply



Submit