Reputation: 4821
I have this code. I am trying to match on .mono-50, where 50 can be any number.
imageUrl = 'http://example.com/media/image.mono-50.png';
imageUrlSplit = imageUrl.split('/.mono-\d+/');
console.log(imageUrlSplit);
This does not match, but does match on my testing tool, regexr.com
I have done many variations on it including the following.
.split('/.mono\-\d+/');
.split('/\.mono\-\d+/');
.split('/.mono-\d+/g');
.split('/.mono\-\d+/g');
.split('/\.mono\-\d+/g');
All of these work in the tool, but none in Javascript. Am I misunderstanding something on how .split()
treats Regex?
I have seen this question, but it has not helped me solve this issue.
Javascript split regex question
Upvotes: 1
Views: 57
Reputation: 626920
You need to use a regex literal notation (when the regex literal is put inside quotes it becomes a regular string literal, and split
uses this text as a literal string, not a pattern) and escape the dot since an unescaped dot in a regex pattern matches any character (but a newline):
imageUrlSplit = imageUrl.split(/\.mono-\d+/);
^^^ ^
See demo:
imageUrl = 'http://example.com/media/image.mono-50.png';
imageUrlSplit = imageUrl.split(/\.mono-\d+/);
console.log(imageUrlSplit);
Upvotes: 2