javascriptregexgulpgulp-replace

reg ex image folder source


I'm trying to create a regex to detect any images reference in HTML, CSS or JavaScript, whilst taking into account the various patterns that image source referencing can take.

This is to modify the url path of all images as part of a gulp-replace task.

These are the instances I think I need to cover

"../img/hero/layer4.png
"../images/bg-top.jpg
'img/logo.jpg
'img/btn/banner-submit.jpg
"img/btn/animated-thank-you-banner.gif

And this is what I have so far for the regex

(?:(\.\.\/)|)(img|imgs|image|images)(.*[\\\/])

https://regex101.com/r/kF7hG0/2

Unfortunately this seems to match the img tag

<img src="img/

How do I modify the reg ex to capture everything after a " or ', essentially the image path without the file name and extension?

The regex is run as part of this gulp task

gulp.task('html', function () {

  gulp.src(source + '**/*.+(html|php)')
    .pipe($.plumber())
    .pipe($.inline({
        base: source,
        js: $.uglify,
        css: $.cleanCss,
        disabledTypes: ['svg', 'img']
    }))
    .pipe($.replace(/("|')(?:(\.\.\/))?(?:img|image|images)(.*[\\\/])/g, '"' + mtkosrc + campaign +'-'))
    .pipe(gulp.dest(build))
});

Thanks


Solution

  • (?:(\.\.\/)|)(?!img src)(img|imgs|image|images)(.*[\\\/])

    I added (?!img src) to your original regex. This is a negative lookahead assertion that the text next to be captured isn't img src.

    For more about lookaround assertions: http://www.regular-expressions.info/lookaround.html

    (This is the quick patch to your existing regex, as I am sure we can rewrite it to make it quicker, and more intuitive.)