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

梦想与她 提交于 2021-02-04 18:15:57

问题


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);
});

回答1:


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'


来源:https://stackoverflow.com/questions/20300616/javascript-regexobj-exec-says-typeerror-pattern-exec-is-not-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!