Check if String starts with http
To check if given string start with the string 'http'
in JavaScript, call startWith() method on the string and pass the string 'http'
as argument in the method call.
The boolean expression to check if the string str
starts with 'http'
is
str.startsWith('http');
If the value is str
starts with 'http
, then the above expression returns true
, or else, the expression returns false
. We can use this expression in an if-else statement as follows.
if (str.startsWith('http') ) {
//str starts with http
} else {
//str does not start with http
}
Examples
In the following example, we take a URL in string str
, check if the string starts with 'http'
, and display the output in pre#output.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output">Output : </pre>
<script>
var str = 'https://www.tutorialkart.com/';
if ( str.startsWith('http') ) {
document.getElementById('output').innerHTML = 'str starts with http';
} else {
document.getElementById('output').innerHTML = 'str does not start with http';
}
</script>
</body>
</html>
Now, let us take another URL in str
, and check if it starts with 'http'
.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output">Output : </pre>
<script>
var str = 'www.tutorialkart.com/';
if ( str.startsWith('http') ) {
document.getElementById('output').innerHTML = 'str starts with http';
} else {
document.getElementById('output').innerHTML = 'str does not start with http';
}
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we learned how to check if given string starts with http using String.startsWith() method, with example program.