Regex in javascript to match partial URL

3

I need to write a javascript regex that contains a specific piece of URL, but I'm not able to do it, mainly because it's a url with "/".

Example: Any "like" or partial match for "www.url.com/foo"

www.url.com/foo/bar/send/123   - true
www.url.com/foo/doe/get/123    - true
www.url.co/foo/doe/get/123     - false
http://www.url.com/foo/get/123 - true
http://www.url.co/foo/doe/123  - false

Any idea how to make a "generic" regex for any other urls as well?

    
asked by anonymous 22.03.2017 / 14:54

3 answers

3

You can use .test from < a reg="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp"> RegExp :

/\w+\.com(\/[\/\w]*)?$/.test(url);

Remembering to escape the "/".

var url = "www.url.com/foo/bar/send/123"; 
var res = /\w+\.com(\/[\/\w]*)?$/.test(url);

console.log(url, ' -> ', res);

var url = "www.url.co/foo/bar/send/123"; 
var res = /\w+\.com(\/[\/\w]*)?$/.test(url);

console.log(url, ' -> ', res);
    
22.03.2017 / 15:00
1

You can use this regex: /(http:\/\/)?www\.\w+\.com.+/g as follows:

var regExp = /(http:\/\/)?www\.\w+\.com.+/g;
var url = 'url-aqui';
var resultado = regExp.test(url); //retorna true ou false

So you get in the URL the http:// that may or may not exist, www , any text that is after, and end the domain with .com .

    
22.03.2017 / 15:07
0

The best to work with url is by it in a string and uses RegExp, as it automatically performs escape from the bars, so you can write your test url normally.

var url = "www.url.com/foo/bar/";
r = new RegExp(url);
console.log(r);

So I understand what you want to check is if the domain is correct for this you can do so.

var dominio = 'www.url.com';
var r = new RegExp(dominio);

console.log(r)

var testes = [
  'www.url.com/foo/bar/send/123',
  'www.url.com/foo/doe/get/123',
  'www.url.co/foo/doe/get/123',
  'http://www.url.com/foo/get/123',
  'http://www.url.co/foo/doe/123',
]

for(var i in testes){
  var url = testes[i];
  console.log(url, url.match(r)!=null);
}

And so to check the url with foo simply change to var dominio = 'www.url.com/foo'

    
22.03.2017 / 15:16