Rosie
Rosie

Reputation: 45

Using regex to remove characters till the last -

I'm new to regex and trying to figure out how to remove characters till the last - in the string. I currently have strings in the format like this:

purple-hoodie.jpg-1625739747918

I am trying to remove characters to essentially be left with:

-1625739747918

Does anyone have any advice on how to approach this? I'm struggling to work out how to indicate to reach the last - in the string, if that is even possible?

Thanks

Upvotes: 1

Views: 54

Answers (3)

Apostolos
Apostolos

Reputation: 10463

Just use lastIndexOf

let str = 'purple-hoodie.jpg-1625739747918'
console.log(str.substring(str.lastIndexOf('-')))

Upvotes: 3

TopW3
TopW3

Reputation: 1527

Here is my solution.

const txt = 'purple-hoodie.jpg-1625739747918';
const result = txt.replace(/-\d+$/, '');
console.log(result)

This removes the last trailing digits prefixed by -.

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520908

I prefer a match approach here:

var input = "purple-hoodie.jpg-1625739747918";
var output = input.match(/-\d+$/)[0];
console.log("match is: " + output);

But this assumes that the input would end in all digits. A more general regex approach might use a replace all:

var input = "purple-hoodie.jpg-1625739747918";
var output = input.replace(/^.*(?=-)/, "");
console.log("match is: " + output);

Upvotes: 0

Related Questions