0

I'm used to using Regex in PHP but haven't really used it much in Javascript; I looked around but couldn't really find an answer other than just a bunch of tutorials on the regex syntax which I don't need.

For example I want to do the below, but with Regex:

if (location != '/group_breaks.php' && location != '/group_breaks' && location != '/group_breaks/') {

}

My regex would be: /^\/group_breaks(\.php|\/)?$/

So I could do this in PHP I could do:

if (!preg_match('/^\/group_breaks(\.php|\/)?$/', $location)) {

}

What is the alternative in Javascript?

3
  • Your regexp doesn't match /group_breaks Commented Dec 19, 2014 at 10:41
  • Sorry, I missed the ?. Edited. Commented Dec 19, 2014 at 10:51
  • No idea why the downvotes, cause I don't know how to implement regex in Javascript? Commented Dec 19, 2014 at 10:56

3 Answers 3

2

You can use RegExp.test which returns a boolean which tells if the string matches or not.

var yourStringHere = "This is a string";
if(/^\/group_breaks(\.php|\/)$/.test(yourStringHere)){
   // valid
}
Sign up to request clarification or add additional context in comments.

Comments

1

In Javascript you can use:

if ( /^\/group_breaks(\.php|\/)?$/.test(location)) {
}

Remember to make (\.php|\/)? part optional so that it matches /group_breaks OR /group_breaks/ OR /group_breaks.php

2 Comments

Yep...... accidentally missed the ? haha, thanks! What about if I wanted to make sure it doesn't match!? Can I put a ! at the start?
Yes sure you can do if ( !/^\/group_breaks(\.php|\/)?$/.test(location) ) {...} as well. Since regex.test method returns boolean
0

Put your regex inside a negative lookahead.

/^(?!\/group_breaks(\.php|\/)?$)/gm

EXample:

> /^(?!\/group_breaks(\.php|\/)?$)/.test("/group_breaks.php")
false
> /^(?!\/group_breaks(\.php|\/)?$)/.test("/group_breaks/")
false
> /^(?!\/group_breaks(\.php|\/)?$)/.test("/group_breaks")
false
> /^(?!\/group_breaks(\.php|\/)?$)/.test("/group")
true

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.