1

I'm getting nowhere with this...

I need to test a string if it contains %2 and at the same time does not contain /. I can't get it to work using regex. Here is what I have:

var re = new RegExp(/.([^\/]|(%2))*/g);
var s = "somePotentially%2encodedStringwhichMayContain/slashes";

console.log(re.test(s))  // true

Question:
How can I write a regex that checks a string if it contains %2 while not containing any / slashes?

Tunaki
  • 132,869
  • 46
  • 340
  • 423
frequent
  • 27,643
  • 59
  • 181
  • 333

3 Answers3

2

Try the following:

^(?!.*/).*%2
Jack
  • 1,064
  • 8
  • 11
2

While the link referred to by Sebastian S. is correct, there's an easier way to do this as you only need to check if a single character is not in the string.

/^[^\/]*%2[^\/]*$/

enter image description here

EDIT: Too late... Oh well :P

Rakesh KR
  • 6,357
  • 5
  • 40
  • 55
Cu3PO42
  • 1,403
  • 1
  • 11
  • 19
1

either use inverse matching as shown here: Regular expression to match a line that doesn't contain a word?

or use indexOf(char) in an if statement. indexOf returns the position of a string or char in a string. If not found, it will return -1:

var s = "test/"; if(s.indexOf("/")!=-1){

//contains "/"

}else {

//doesn't contain "/" }

Community
  • 1
  • 1
sebastian s.
  • 160
  • 4
  • thanks. I also was looking at indexOf but I was looking if it could be done with regex, too. Checking the link – frequent Jan 18 '14 at 14:06