Citizen602214085
Citizen602214085

Reputation: 163

Regex issue with version of Chrome

I want to get a string from an picture's url with regular expression using match() in javascript. I have tested it on a Chrome version 62 and it works great, but in a lower version (e.g. 58) it doesn't work! This is my two lines of code where the issue comes from :

// cloneURL = "/assets/images/bonhommeneige.png"
var cloneName = cloneURL.match('(?<=images/)(.*?)(?=.png)');

On my Chrome v. 62 it gives me "bonhommeneige" but in Chrome v. 58 I have an error : Invalid regular expression. What is wrong with my regular expression?

Upvotes: 1

Views: 977

Answers (3)

Slai
Slai

Reputation: 22876

If you just need the value between the last / and last . (and don't forget to escape . with \.) :

cloneURL = "/assets/images/bonhommeneige.png"

console.log( cloneURL.match(/[^/]+(?=\.)/)[0] )

console.log( cloneURL.match(/([^/]+)\./)[1] )

Upvotes: 1

Zahid Saeed
Zahid Saeed

Reputation: 172

If you want to get the image name, you can try using the following method:

// Method 1

let cloneUrl  = "/assets/images/bonhommeneige.png";
let imageName = cloneUrl.substring (
  cloneUrl.lastIndexOf("/") + 1,
  cloneUrl.lastIndexOf(".")
);

console.log(imageName);

// Method 2

let matches = cloneUrl.match(/(?:images\/)(\S+)(?:\.png)/);

console.log(matches); // Get the [1] index

Upvotes: 1

dfsq
dfsq

Reputation: 193261

Positive lookbehind is not supported in chrome v58. Change your regexp, you can do it without lookbehind anyway. For example you could use non capturing group instead (?:images/):

var cloneURL = "/assets/images/bonhommeneige.png"
var cloneName = cloneURL.match('(?:images/)(.*?)(?=.png)');

console.log(cloneName);

Upvotes: 3

Related Questions