Check if URL starts with “http”
Given a URL as a string, check if the URL starts with the prefix string http
using JavaScript.
Solution
To check if a string starts with a specific prefix string using JavaScript, we can use String.startsWith() method. Call startsWith()
method on the string, and pass the prefix string 'http'
as argument.
startsWith()
returns true
if the string starts with the given prefix string 'http'
, or false
otherwise.
Program
1. Given string is str
and prefix string is 'http'
. Check if string str
starts with the prefix string.
url = "hello world";
prefix = "http";
if ( url.startsWith(prefix) ) {
console.log('url starts with http');
} else {
console.log('url does not start with http');
}