Kosmetika
Kosmetika

Reputation: 21304

Regex: Match url string in the middle of another string

Learning regexp but currently I'm a bit stucked with such pattern..

I need to match my string inside url string, example:

If url contains string '/example/regex' it should return true.

/REGEXFOR:'/example/regex'/.test('http://test.com/example/regex/new') // => true
/REGEXFOR:'/example/regex'/.test('http://test.com/example/regex/new/boo') // => false

Thanks!

Upvotes: 0

Views: 837

Answers (2)

Scipion
Scipion

Reputation: 1380

in your case using $ you can indicate the end of the regex

/\/example\/regex\/\w*$/.test('http:\/\/test.com\/example\/regex\/new') => true
/\/example\/regex\/\w*$/.test('http:\/\/test.com\/example\/regex\/new\/boo') => false

if you don't want any slash more use \w* for letters and numbers characters

Upvotes: 1

melwil
melwil

Reputation: 2553

You just escape the backslash and you need to clean it a bit;

 /\/example\/regex/.test('http://test.com/example/regex/new/boo')

According to what you gave as examples, both should validate, though.

Upvotes: 0

Related Questions