frequent
frequent

Reputation: 28533

How to regex test a string for a pattern while excluding certain characters?

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?

Upvotes: 1

Views: 107

Answers (3)

Cu3PO42
Cu3PO42

Reputation: 1473

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

Upvotes: 2

sebastian s.
sebastian s.

Reputation: 160

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 "/" }

Upvotes: 1

Jack
Jack

Reputation: 1084

Try the following:

^(?!.*/).*%2

Upvotes: 2

Related Questions