2

I need a regular expression for:

-[n digits]x[n digits]

I already tried this:

var s = "path/path/name-799x1024.jpg"; 
s.replace(/\d/g, "");

But this gets only the digits. Here is a small jsfiddle: http://jsfiddle.net/aq6dp49n/

The outcome I try to get is:

pfad/pfade/name.jpg

How do I add the - and the small x between the two digits?

Jonny Vince
  • 487
  • 2
  • 9

2 Answers2

5

The regular expression that would match that is /-\d+x\d+/. Hence:

s.replace(/-\d+x\d+/, "")

Should work.

Here's what the regex means: the first - tells it that it should look for a - character. Then you have \d+ which means "one or more of \d", where \d is short-hand for the character class [0-9], i.e., all digits. After that you have x, which means it will look for the character x, and finally you have \d+ again, which is the same as before.

Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295
  • One fateful day many years ago I decided to learn perl, which led me to learning regex. :) I've also added an explanation about the meaning of the regex. – Vivin Paliath Jul 29 '15 at 16:22
1

To match

-[n digits]x[n digits]

You would want

match(/-[0-9]{n}x[0-9]{n}\b/)

Though if you want an arbitrary (one or more) number of digits, use + in place of {n}. In the case of your example, you'd want 3 and 4 for your values of n.

Here's a step-by-step explanation of what this does:

/-[0-9]{3}x[0-9]{4}\b/

    - matches the character - literally
    [0-9]{3} match a single character present in the list below
        Quantifier: {3} Exactly 3 times
        0-9 a single character in the range between 0 and 9
    x matches the character x literally (case sensitive)
    [0-9]{4} match a single character present in the list below
        Quantifier: {4} Exactly 4 times
        0-9 a single character in the range between 0 and 9
    \b assert position at a word boundary (^\w|\w$|\W\w|\w\W)

To remove the last size-like part of a string, this should do:

"path/path/name-799x1024.jpg".replace(/(.*)-[0-9]+x[0-9]+/, "$1");
// "path/path/name.jpg"
"path/path/name-10x12-799x1024.jpg".replace(/(.*)-[0-9]+x[0-9]+/, "$1");
// "path/path/name-10x12.jpg"

This takes advantage of the fact that regexps are greedy, so the (.*) absorbs (and saves) as much preceding text as possible before finding the next match.

(I prefer to use [0-9] in place of \d because it's more specific (\d also matches non-latin numerals) and therefore slightly faster, though in this case it shouldn't matter.)

Adam Katz
  • 14,455
  • 5
  • 68
  • 83