Search code examples
javascriptregexwordpressmootools

JavaScript - Regular expression to convert image source


My question is related only to JavaScript regular expressions.

I'm building a simple Lightbox for Wordpress with Mootools JavaScript framework.

Wordpress stores pictures in a variety of sizes with file names like:

'image-50-50x100.jpg'
'image-50-150x100.jpg'
'image-50-1024x698.jpg'
'image-50.jpg'

When a user clicks a thumbnail image, I have to convert the source of that image into the source of full size image, and then preload that full-size image.

The question

How to change string like this:

'http://some-path/image-50-50x100.jpg'
'http://some-path/image-50-150x100.jpg'
'http://some-path/image-50-1024x698.jpg'
'http://some-path/image-50.jpg'

, into:

'http://some-path/image-50.jpg'

Missing piece is accurate regular-expression in code below:

source.replace( /regular-expression/, '' );

Thanks in advance.


Solution

  • This should do it:

    str = str.replace(/-\d+x\d+/, '');
    

    E.g.:

    var str = 'http://some-path/image-50-1024x698.jpg';
    str = str.replace(/-\d+x\d+/, '');
    console.log(str); // "http://some-path/image-50.jpg"
    

    And for the case where you don't want it to change, it doesn't:

    var str = 'http://some-path/image-50.jpg';
    str = str.replace(/-\d+x\d+/, '');
    console.log(str); // "http://some-path/image-50.jpg"
    

    Edit: You've said in a comment elsewhere that:

    In some rare cases it can happen that Wordpress user uploads image like image-1024x698.jpg, then Wordpress creates thumb image like image-1024x698-300x300.jpg

    Okay, so we add \. and . to the above:

    var str = 'http://some-path/image-1024x698-300x300.jpg';
    str = str.replace(/-\d+x\d+\./, '.');
    console.log(str); // "http://some-path/image-1024x698.jpg"