0

Using javascript I need to rename some urls in a document to file names.

Router.route('/photos')
    .get(function(req, res){

        models.PHOTOS.find({}, function(err, photos){
            if (err) {
                res.status(500).send(err);
            }
            else {
                var input = JSON.stringify(photos);
                var output = input.replace('http://www.someurl.com/media.ashx?id=', '').replace('&t=pi&f=I', '.jpg');
                res.json(JSON.parse(output));
            }
        });
    });

So from http://www.someurl.com/media.ashx?id=FILE123456&t=pi&f=I I should obtain FILE123456.jpg

But it only changes it for the first matching string and I would like to do it for the entire document.

1 Answer 1

1

use regex and global, /g, some thing like

var output = input.replace(/http\:\/\/www\.someurl\.com\/media\.ashx\?id=/g, '').replace(/&t=pi&f=I/g, '.jpg');

Edit: you know what, a cleaner way to do it might be ( assuming structure to be photos being array of photo object with url as attribute) :

Router.route('/photos')
    .get(function(req, res){

        models.PHOTOS.find({}, function(err, photos){
            if (err) {
                res.status(500).send(err);
            }
            else {
                photos.forEach(function(photo){
                    photo.name = photo.url.replace(/http\:\/\/www\.someurl\.com\/media\.ashx\?id=/, '').replace(/&t=pi&f=I/, '.jpg');
                });
                res.json(photos);
            }
        });
    });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.