Gab
Gab

Reputation: 2276

Using javascript I need to replace matching strings in document

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.

Upvotes: 0

Views: 26

Answers (1)

mido
mido

Reputation: 25044

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);
            }
        });
    });

Upvotes: 1

Related Questions