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

evaldasburlingis

Evaldas

Posted on September 11, 2020

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

💖 💪 🙅 🚩
evaldasburlingis
Evaldas

Posted on September 11, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related