The startsWith() Function is used to check if a String begins with a particular Substring.
<html> <body> <script> var x = "Hello Beautiful World" var y = x.startsWith("Hello") if (y == true) { document.write("The String starts with Hello") } else { document.write("The String does not start with Hello") } </script> </body> </html>
In the above code, we have declared a String Hello Beautiful World and assigned it to a variable x.
x = "Hello Beautiful World"
And we have checked if the String, Hello Beautiful World starts with the substring Hello.
if (y == true) { document.write("The String starts with Hello") } else { document.write("The String does not start with Hello") }
And in this case the String, substring Hello Beautiful World starts with the substring Hello
And thus we get the below output.
The String starts with Hello
Now, let us say we have the below String,
"Hello World"
And we want to check if the above String starts with the substring World.
Well! Certainly the substring World is not the substring that the above String starts with.
But we know that the substring World starts from the position 6.
And luckily, JavaScript provides a second and third parameter that specifies the range.
Let us see with the below example.
<html> <body> <script> var x = "Hello World" var y = x.startsWith("World", 6, 11) if (y == true) { document.write("The String starts with World from a specific position") } else { document.write("The String does not start with World from the specific position") } </script> </body> </html>
In the above code, we have declared a String Hello World and assigned it to a variable x.
var x = "Hello World"
And we have checked if the String, Hello World starts with the substring World. And specified the range from 6 to 11 in the x.startsWith("World", 6, 11) function.
if (y == true) { document.write("The String starts with World from a specific position") } else { document.write("The String does not start with World from the specific position") }
And found that the substring World starts from the location 6.
So, we get the below output.
The String starts with World from a specific position