Regex to test if string begins with http:// or https://


🔍 Regex to test if string begins with http:// or https://
Are you struggling with creating a regex pattern to check if a string starts with either "http://" or "https://" 🤔? Don't worry, you're not alone! Many developers face this challenge when working with regular expressions. But fear not, I'm here to help you find an easy solution to this problem! 🙌
🤔 The issue:
The code you provided, ^[(http)(https)]://
, unfortunately, won't do the trick. Let me explain why. The square brackets [ ]
used in regular expressions indicate character sets or groups. In your case, the character set includes the letters "http" and "https", which means it will look for any occurrence of these letters, individually, at the beginning of the string. That's not what you want, right? 🙅♀️
🚀 The solution:
To accomplish your goal, you can use the pipe symbol |
which means "or" in regular expressions. Here's the correct regex pattern:
^(http|https)://
Let's break down the pattern:
^
asserts the beginning of the string.(http|https)
matches either "http" or "https".://
matches the literal characters "://".
So, this pattern ensures that the string starts with either "http://" or "https://"! 🎉
✨ Example usage:
Let's see some examples to illustrate how this regex can be used properly:
const regex = /^(http|https):\/\//;
console.log(regex.test("http://www.example.com")); // true
console.log(regex.test("https://www.example.com")); // true
console.log(regex.test("ftp://www.example.com")); // false
console.log(regex.test("https://example.com")); // true
console.log(regex.test("http://example.com")); // true
As you can see, the regex successfully matches the URLs that begin with "http://" or "https://". 🎯
📣 Call-to-action:
Now that you have a solid understanding of the correct regex pattern to test if a string begins with "http://" or "https://", it's time to put it into action! Try it out in your own code and let me know how it works for you! I'd love to hear about your experiences or any other regular expression challenges you may have. So go ahead and leave a comment below! 💬
Happy coding! 😄
Take Your Tech Career to the Next Level
Our application tracking tool helps you manage your job search effectively. Stay organized, track your progress, and land your dream tech job faster.
