Goose
Goose

Reputation: 4821

Regex isn't matching on Javascript .split() but does match on testing tool

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

http://regexr.com/3e55b

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

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

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

Related Questions