DEV Community

Evaldas
Evaldas

Posted on

1

JavaScript snippet: get trailing information after ("/", "-", "etc")

Recently I've been working on a job board website. It has URL structure as follows: "job/shopify-rails-junior-dev-4d5as18184das". Everything after last dash(-) is id in the database about this specific job ad. To extract it I wrote a short and simple function that allows you to get everything after the last slash, dash, etc.

Javascript:

const test1 = "/shopify/php-programmer-4781"
const test2 = "/shopify/rails/1351"

function getTrailingId(punctuation, str)  {
    const trailingId = str.substr(str.lastIndexOf(punctuation) + 1)
    return trailingId
}

getTrailingId("-", test1) // 4781
getTrailingId("/", test2) // 1351

Typescript:

const test1 : string = "/shopify/php-programmer-4781"
const test2 : string = "/shopify/rails/1351"

function getTrailingId(punctuation: string, str: string) : string {
   const trailingId : string = str.substr(str.lastIndexOf(punctuation) + 1)
   return trailingId
}

getTrailingId("-", test1) // 4781
getTrailingId("/", test2) // 1351

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay