android
android

Reputation: 652

Match strings which do not start or end with

How can I test a string if it begins with "files/" and/or ends with ".js"?

Examples:

So far I have this regular expression: (^(?!files\/)).*?((?!\.js)$)

This works for "files/" but not for ".js".

Edit: Sorry for the misunderstanding. The string should only match if a string does NOT start with "files/" and does NOT end with ".js".

Upvotes: 1

Views: 6538

Answers (5)

user1726343
user1726343

Reputation:

Here is a regex that does what you need.

(^(?!files\/)).*((?!\.js).{3}$)

You were checking if the last character did not have ".js" in front of it, which is always true.

Upvotes: 2

trumank
trumank

Reputation: 2794

!/^files\/|\.js$/.test('files/test2/test.js') -> false
!/^files\/|\.js$/.test('files/test2/test.html') -> false
!/^files\/|\.js$/.test('test/test2/test.js') -> false
!/^files\/|\.js$/.test('test/test2/test.html') -> true

Upvotes: 1

sainiuc
sainiuc

Reputation: 1697

var re = /^files\/.*|.*\.js$/;
alert(re.test('your-strings'));

EDIT

No worries, just invert the result:

var re = /^files\/.*|.*\.js$/;
alert(!re.test('your-strings'));

Upvotes: 1

Bob Vale
Bob Vale

Reputation: 18474

Your last negative should be a look behind not a look ahead, At the point of the test you've already read the .js

^(?!files\/).*(?<!\.js)$

Upvotes: 5

Anirudha
Anirudha

Reputation: 32827

You can use this regex

^(files/.*|.*\.js)$

Since you dont want strings ending or starting with files and or js,use the above regex and do this

if(/*regex matches the string*/)
{
//you dont need this string
}
else
{
//you do need this string
}

Upvotes: 1

Related Questions