-1

I want to extract a string of a URL that follows the same pattern:

http://www.website.com/abcd/efg/xyz/the_string_i_want/?Cr=47

I would like to extract only "the_string_i_want"

nnnnnn
  • 147,572
  • 30
  • 200
  • 241

3 Answers3

4

var a="http://www.website.com/abcd/efg/xyz/the_string_i_want/?Cr=47";
var b=a.split("/");
console.log(b[b.length-2]);
Mahi
  • 1,707
  • 11
  • 22
2

Split the string on slashes and return the next-to-last segment:

const url = 'http://www.website.com/abcd/efg/xyz/the_string_i_want/?Cr=47';
const segs = url.pathname.split('/');
console.log(segs[segs.length - 2]);

If for some reason you want to use a regexp, create one which starts with a slash, takes other non-slash characters ([^\/]]) up to another slash (and captures them (())), and then more non-slash characters up to the end of the string ($).

var str = 'http://www.website.com/abcd/efg/xyz/the_string_i_want/?Cr=47';

console.log(str.match(/\/([^\/]*)\/[^\/]*$/)[1]);
//                     ^^                         START WITH SLASH
//                       ^^^^^^^^                 CAPTURE THE PART YOU WANT
//                               ^^               ANOTHER SLASH
//                                 ^^^^^^         MORE NON-SLASHES
//                                       ^        END OF STRING

However, whether you use split or regexp, in general parsing URLs is cumbersome and fragile. You should use a regexp parsing library. For instance, such libraries will handle issues such as / vs. \ as a path separator, and/or normalize the URL for trailing slashes.

0

Try this Regex

http(?:s)?\:\/\/www\.\w+\.[\w]{2,}\/(?:(\w+)\/)+(?:\?\w+\=\w+)?

https://regex101.com/r/MtEwQ7/2

Vijay Wilson
  • 516
  • 7
  • 21