Parsing an image name from an img tag with a regular expression

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

Now I have successfully received the tag <img>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 a line placeholderdefault.jpg.

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

Now the problem is that it returns null, even if the value bigImageSrcishttp://localhost/yogurtbar/images/slider/placeholderdefault.jpg

I do not understand why it does not detect placeholderdefault.jpgin the string. I tried (and produced) this regex in Regexr and it works.

What am I doing wrong in my code?

+4
source share
3

g .

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

p (in placeholder) charcater g, .

,

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

, , jpg jpeg.

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

regex.\

indexOf. regex:

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

regex:

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

.

+3

An easy way would 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
Run code
0
source

Source: https://habr.com/ru/post/1589135/


All Articles