简体   繁体   中英

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.

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM