简体   繁体   中英

JS Regexp to exclude forward slash after .com in url

I have this URL for eg https://www.example.com/filters/test.jpg and in JS, I want to retrieve this part: filters/test.jpg .

I am using match() but the element of the first position of match is /filters/test.jpg .

This is my regexp: /(?.com)\/((\w+)\/(.*))/

What am I missing to remove the forward slash / from the match array?

If your interest is in regex itself rather than just the result, how about this expression?

(?<=.+\.com\/).+

This uses a positive lookbehind and will give you everything after any amount of text ending in ".com/". Note my use of escape slashes for the period and the forward slash. If you want more specificity, you can do the same thing with the word group and second slash in your original regex:

(?<=.com\/)((\w+)\/(.*))

UPDATE: As requested, a note on negative vs. positive lookahead/lookbehind: lookahead instructs the query to "look for X, but match only if followed by Y." Negative lookahead "look for X, but match only if not followed by Y." In your case, you want a lookbehind because that will "look for X, but match only if preceded by Y." A negative lookbehind, which you were trying, allows to match a pattern only if there isn't something before it, so doing this in your case would be a mistake. For more information, see https://javascript.info/regexp-lookahead-lookbehind

If your goal is just to get the result, I think using the URL object in javascript (as in the comment) is actually better than regex because it's more tuned to the specific problem. See https://dev.to/attacomsian/introduction-to-javascript-url-object-27hn .

If code for new JS engines /(?<=\/)(\w+)\/.*/

If code for old JS engines /\b(??(:.com|net|org|uk)\/)(\w+)\/.*/

Best way though is store array using /\/((\w+)\/.*)/

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