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

javascript, jquery, regex, url

Solution

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

Creates a string. A string has no method `exec`. You meant a `RegExp` literal:

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

I suppose you might as wel use the `RegExp.test` method here, if all you need is confirmation that `src` complies to the given pattern:

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

If you need a matched 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'

Problem

I want to extract image name from img tag with regex 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); }); ```

Original source