Javascript regexObj.exec () says TypeError: pattern.exec is not a function

I want to extract image name from img tag using regular expression in javascript . My problem is that console.log()throws exception TypeError: pattern.exec is not a function.

JS:

$("label.btn-danger").on('click',function(e){
    e.preventDefault();
    var src = $(this).parents("label").find("img").attr("src");
    var pattern = "/\/([A-Z0-9_-]{1,}\.(?:png|jpg|gif|jpeg))/ig";
    var result = pattern.exec(src)
    console.log(result);
});
+4
source share
1 answer
var pattern = "/\/([A-Z0-9_-]{1,}\.(?:png|jpg|gif|jpeg))/ig";

Creates a string. The string has no method exec. Did you mean the literal RegExp:

var pattern = /\/([A-Z0-9_-]{1,}\.(?:png|jpg|gif|jpeg))/ig;

I believe that here you can use the method RegExp.testif you only need confirmation that srcmatches the given pattern:

var result = /\/([A-Z0-9_-]{1,}\.(?:png|jpg|gif|jpeg))/ig.test(src);

If you need a matching value, use RegExp.match:

var result = src.match(/\/([A-Z0-9_-]{1,}\.(?:png|jpg|gif|jpeg))/ig);
// let src be '../images/someimage.png'
// then result[0] = '/someimage.png'
+7

All Articles