Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
});
like image 766
Ramin Omrani Avatar asked Nov 30 '13 13:11

Ramin Omrani


1 Answers

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'
like image 148
KooiInc Avatar answered Oct 11 '22 03:10

KooiInc