简体   繁体   中英

parsing image name from img tag with regex

I have an <img> tag inside a div where i want to get the image name through javascript and regex.

Now, I successfully retrieved the <img> tag as a string.

var bigImage = $(this).find('.img-container img')
var bigImageSrc = bigImage[0].src
var regx = /g\bplaceholderdefault\.jpg?\b/g
var match = bigImageSrc.match(regx)

I want this expression to see if there is placeholderdefault.jpg in the string.

By the way, bigImageSrc returns a valid string, as I checked it with typeof

Now the problem is it returns null even if bigImageSrc 's value is http://localhost/yogurtbar/images/slider/placeholderdefault.jpg

I don't get why it doesn't detect placeholderdefault.jpg in the string. I tried (and produced) this regular expression in Regexr and it works.

What am I doing wrong in my code?

There is no need of regex .\\

You can use indexOf . This will run faster as compared to regex :

if (bigImageSrc.indexOf('placeholderdefault.jpg') > -1) {
    // Present

If you want to check it with regex :

if (/placeholderdefault\.jpg/.test(bigImageSrc)) {
    // Present
}

You need to escape .

You need to remove the g present at the start.

var regx = /g\bplaceholderdefault\.jpg?\b/g;
            ^
            |

Since there isn't a charcater g exists before p (in placeholder), your regex fails to find a match.

correct one would be,

var regx = /\bplaceholderdefault\.jpg?\b/g;

and also, I think you want to match both jpg and jpeg formats.

var regx = /\bplaceholderdefault\.jpe?g\b/g;

Easy way will be to get the image name using split()

 var bigImageSrc = 'http://localhost/yogurtbar/images/slider/placeholder-default.jpg'; var filename = bigImageSrc.split("/").pop(); console.log(filename); //output placeholder-default.jpg 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM