5

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);
});
9
  • 3
    Remove the quotes, now you just have a string ? Commented Nov 30, 2013 at 13:08
  • 2
    var pattern = /\/([A-Z0-9_-]{1,}\.(?:png|jpg|gif|jpeg))/ig; Commented Nov 30, 2013 at 13:08
  • thanks, 1 more Q: this returns an array with 2 indexes? Commented Nov 30, 2013 at 13:10
  • 1
    Yes [0] element will be full matched input and [1] will be first matched group. Commented Nov 30, 2013 at 13:11
  • 1
    Try changing .attr("src") to prop("src") and see what happens Commented Nov 30, 2013 at 13:20

1 Answer 1

9
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'
Sign up to request clarification or add additional context in comments.

1 Comment

I can't extract the image name with result[1]. what should I do?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.