F. Vosnim
F. Vosnim

Reputation: 574

How to get last occurrence with regex javascript?

Could you help me extract "women-watches" from the string:

https://www.aliexpress.com/category/200214036/women-watches.html?spm=2114.search0103.0.0.160b628cMC1npI&site=glo&SortType=total_tranpro_desc&g=y&needQuery=n&shipFromCountry=cn&tag=

I tried

\/(?:.(?!\/.+\.))+$

But I don't know how to do it right.

Upvotes: 0

Views: 49

Answers (1)

The fourth bird
The fourth bird

Reputation: 163207

One option could be to use a capturing group to match a word character or a hyphen. Your match will be in the first capturing group.

^.*?\/([\w-]+)\.html

That will match:

  • ^ Start of the string
  • .*? Match any character except a newline non greedy
  • \/ Match /
  • ([\w-]+) Capturing group to match 1+ times a wordcharacter of a hyphen
  • \.html Match .html

Regex demo

const regex = /^.*?\/([\w-]+)\.html/;
const str = `https://www.aliexpress.com/category/200214036/women-watches.html?spm=2114.search0103.0.0.160b628cMC1npI&site=glo&SortType=total_tranpro_desc&g=y&needQuery=n&shipFromCountry=cn&tag=`;
console.log(str.match(regex)[1]);

Another option to match from the last occurence of the forward slash could be to match a forward slash and use a negative lookahead to check if there are no more forward slashes following. Then use a capturing group to match not a dot:

\/(?!.*\/)([^.]+)\.html

Regex demo

const regex = /\/(?!.*\/)([^.]+)\.html/;
const str = `https://www.aliexpress.com/category/200214036/women-watches.html?spm=2114.search0103.0.0.160b628cMC1npI&site=glo&SortType=total_tranpro_desc&g=y&needQuery=n&shipFromCountry=cn&tag=`;
console.log(str.match(regex)[1]);

Without using a regex, you might use the dom and split:

const str = `https://www.aliexpress.com/category/200214036/women-watches.html?spm=2114.search0103.0.0.160b628cMC1npI&site=glo&SortType=total_tranpro_desc&g=y&needQuery=n&shipFromCountry=cn&tag=`;
let elm = document.createElement("a");
elm.href = str;
let part = elm.pathname.split('/').pop().split('.')[0];
console.log(part);

Upvotes: 1

Related Questions