Aaron
Aaron

Reputation: 98

How to use regular expressions to update images that have paths and those without paths

The plan is to update the path, and those that lack a path, with the path to the CDN. Basic example:

var thePath = 'http://media.dev.com.edgesuite.net/is/image/';

...
return value.replace( /[\/]|[\.\w\/].*[\/]/gm, thePath );

But the problem is, some do not have a path...

(/images/bird.gif) has the path of /images/
(/gator.gif) has the path of /
(bird.gif) lacks a path

I am having a difficult time targeting those without a path. The regular expression in action can be seen at http://www.regexr.com/3bj6g.

To provide more context, here is the script...

var scene7 = {
  path  : 'http://media.dev.com.edgesuite.net/is/image/',
  jpg   : '?scl=1&fmt=pjpeg&qlt=25,1',
  gif   : '?scl=1&fmt=gif-alpha&quantize=adaptive,off,256',
  png   : '?scl=1&fmt=png-alpha'
};    

var destAssetsDesktopStandard = {
  html    : basePath.desktopStandard + ''
};

////////////////////////////////////////////////

function replaceImageType( value ) {

console.log(value);

    return value.replace( /[\/]|[\.\w\/].*[\/]/gm, scene7.path )
                .replace( '.jpg', scene7.jpg )
                .replace( '.jpeg', scene7.jpg )
                .replace( '.png', scene7.png )
                .replace( '.gif', scene7.gif );

}

var findImagesInCSS   = '\\(([\\.\\~\\"\\s\\\'\\-\\w\\/]+(\\.(png|jpg|jpeg|gif))).*?\\)';
var replaceWithRegExp = new RegExp(findImagesInCSS, 'gm');

////////////////////////////////////////////////

gulp.task('inline-code', function(){

  var optionsIgnoreScript = { ignore: ['script'] };
  var optionsIgnoreCSS    = { ignore: ['css'] };

  return gulp.src('index.asp')
    .pipe(inlinesource(optionsIgnoreScript))
    .pipe(replace( replaceWithRegExp, replaceImageType ))
    .pipe(inlinesource(optionsIgnoreCSS))
    .pipe(gulp.dest(destAssetsDesktopStandard.html));
});

gulp.task('build-desktop-standard', ['inline-code']);

How would you approach this problem?

Upvotes: 0

Views: 98

Answers (1)

klenium
klenium

Reputation: 2607

If there's nothing you can replace, don't use the regex replace:

if (value.indexOf("/") == -1)
    value = scene7.path;
else
    value = value.replace( /[\/]|[\.\w\/].*[\/]/gm, scene7.path );
return value.replace('.jpg' ...

Upvotes: 1

Related Questions