2

I'm trying to validate a string with regex in javascript that a user inputs into a <form>that starts with http:// and contains a ~ somwhere within that string. what I have is

(/^(http?:\/\/)\~/.test(string))

But it's not quite working.

Any tips?

4
  • 2
    If ( str.indexOf('http://') === 0 && str.indexOf('~') > 0 ) ??? Commented Apr 21, 2016 at 2:58
  • @adeneo Thanks that worked! Can you explain how indexOf works? and what's the difference between == and ===? Commented Apr 21, 2016 at 3:01
  • 1
    @Enigma it gives you the starting index of the substring in the given string.. Commented Apr 21, 2016 at 3:04
  • 1
    String.indexOf gives you the index of the string inside the string. If that index is 0, the string starts with that string. If it's more than 0 it contains the string, if it's -1 it does not contain the string. Commented Apr 21, 2016 at 3:05

3 Answers 3

3

No need or RegEx, you can use String#startsWith and String#includes.

if (str.startsWith('http://') && str.includes('~')) {

As these methods are not supported by all the browsers, you can use polyfills from MDN for older browsers.

Sign up to request clarification or add additional context in comments.

1 Comment

Cool, that worked as well! It's neat how there's multiple methods to solve this problem.
1

The regex solution would look like:

(/^https?:\/\/.*\~/.test(string))

Your regex was almost correct, you were just missing the .* which checks for characters after the http:// portion

I also put s? in there in-case https was valid

2 Comments

Why did you escape ~ actually?
Well honestly, I included the escape because the OP had it escaped. Figured it might be special in JS. Does it hurt anything? I know it worked in the console when I tested it.
1

I think your regex should be repaired to this:

(/^(http?:\/\/).*\~/.test(string))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.