shaithana
shaithana

Reputation: 2490

Find particular string inside URL with Regex

I need to "regex" – in JavaScript – a string like:

http://some.domain.com/v/v1.0-4/19232_102032_21111986_n.jpg?param=fejrlwfje&list=fklwefljfre

I need to extract 19232_102032_21111986_n, that is, just the name of the image between http://some.domain.com/v/v1.0-4/ and .jpg?param=fejrlwfje&list=fklwefljfre, and assign it to a variable.

Upvotes: 1

Views: 4166

Answers (4)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626929

You can use

\/([^\/?]+)\.jpg(?:\?|$)

See the regex demo

Pattern description:

  • \/ - a slash
  • ([^\/?]+) - Group 1 (the file name) matching 1 or more characters other than / and ?
  • \.jpg - a literal .jpg
  • (?:\?|$) - a non-capturing group matching either ? or the end of string.

var s = 'http://some.domain.com/v/v1.0-4/19232_102032_21111986_n.jpg?param=fejrlwfje&li‌st=fklwefljfre';
var m  = s.match(/\/([^\/?]+)\.jpg(?:\?|$)/);
document.body.innerHTML = m ? m[1] : "No match!";

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

As an alternative, it can be achieved without regex by using String.split, String.substr and Array.lastIndexOf functions:

var url = "http://some.domain.com/v/v1.0-4/19232_102032_21111986_n.jpg?param=fejrlwfje&list=fklwefljfre",
    url_part = url.split("?")[0],
    img_file = url_part.substr(url_part.lastIndexOf("/")+1).split(".")[0];

console.log(img_file);   // "19232_102032_21111986_n"

Upvotes: 0

Richard
Richard

Reputation: 1041

Assuming that there is no '?' in the string you want to match, you can try :

/\/([^?/]*)(\?|$)/.exec("http://some.domain.com/v/v1.0-4/19232_102032_21111986_n.jpg?param=fejrlwfje&list=fklwefljfre")[1].slice(0,-4)

This will match all characters after the last '/', that are not '/' or '?' and before '?' or the end of the string.

The slice call is used to removed the '.jpg' part.

Upvotes: 0

k102
k102

Reputation: 8079

Try this:

var s = "http://some.domain.com/v/v1.0-4/19232_102032_21111986_n.jpg?param=fejrlwfje&list=fklwefljfre"
var result = /\/([a-z_0-9]+)\.jpg/.exec(s)[1];

Upvotes: 0

Related Questions