1

I can't get those RegEx pattern to work with JavaScript (in PHP they work):

/^[^\/home\/]/
/^\/home\/$/
/^\/home\/.+\/.+$/

I want to allow input like this:

/home/username

What I don't want is:

/home/
/username
/home/username/info

Here is my code:

var regex1 = /^[^\/home\/]/;
var regex2 = /^\/home\/$/;
var regex3 = /^\/home\/.+\/.+$/;
if( regex1.test(homedir)
|| regex2.test(homedir)
|| regex3.test(homedir) ) { ... }

I have no errors in the console.

Could someone explain to me why it is not working in JavaScript?

EDIT

I changed it to /^\/home\/[A-Za-z0-9]+$/ and now it's working:

var rgx = /^\/home\/[A-Za-z0-9]+$/;
if( !rgx.test(homedir) ) { ... }
14
  • 2
    plz post your input string and expected output Commented Apr 30, 2018 at 17:58
  • 1
    "why it is not working in JavaScript" could you tell what is not working? there's some errors in the console? are you trying to replace or to find something with this regex? Please, be more specific Commented Apr 30, 2018 at 17:58
  • 1
    Possible duplicate of what is the difference between PHP regex and javascript regex Commented Apr 30, 2018 at 18:00
  • 1
    Thank you very much @sln - yes, I agree to the fact that I maybe have to rewrite it. I Just wanted to understand the difference as in PHP it's working. Commented Apr 30, 2018 at 18:19
  • 1
    I rewrote it to /^\/home\/[A-Za-z0-9]+$/ and it's working fine as I now check if the string matches instead of checking if it doesn't match, just as @sln suggested. Thank you all for you help :) Commented Apr 30, 2018 at 18:38

1 Answer 1

0

Remove the string start Regex parameter ^

You will now have: \/home\/.+\/.+$

Example built here showing validation: Regex Home URL example

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

2 Comments

Thank you, I did that (removed the ^). I now matches also valid input like /home/username.
Regexr is a great tool to help you build and validate regular expressions

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.