如何使用正则表达式更新具有路径和没有路径的图像

时间:2015-08-14 17:02:19

标签: javascript regex gulp

计划是使用CDN的路径更新路径和缺少路径的路径。基本示例:

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

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

但问题是,有些人没有路径......

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

我很难找到那些没有路径的人。可以在http://www.regexr.com/3bj6g看到正则表达式。

为了提供更多上下文,这里是脚本......

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']);

你会如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

如果您无法替换,请不要使用正则表达式替换:

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