Reputation: 1167
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?
Upvotes: 4
Views: 822
Reputation: 87203
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 .
Upvotes: 3
Reputation: 174696
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;
Upvotes: 2
Reputation: 3520
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
Upvotes: 0