1

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

Community
  • 1
  • 1
Goose
  • 4,764
  • 5
  • 45
  • 84
  • Remove the single quotes, as you're splitting on a string rather than a pattern. – John Aug 31 '16 at 22:15
  • @Trey: Not only. The dot must be escaped, too. OP is not sure whether it must be escaped or not. – Wiktor Stribiżew Aug 31 '16 at 22:16
  • @WiktorStribiżew correct, but he has escaped them in some of his attempts so I didn't mention it – John Aug 31 '16 at 22:17
  • `'/\.mono\-\d+/g'` -> the literal string that starts with forward slash contains "mono" and finishes on forward slash and "g". `/\.mono\-\d+/g` the regex that matches a pattern that contains a literal dot, followed by "mono" dash and any number of digits. – VLAZ Aug 31 '16 at 22:18
  • If the dot is unescaped, then `'http://example.com/media/demono-60/image.mono-50.png'` would get split incorrectly. @Vld: the global behavior is default with `split()`. A second argument controls that side of splitting. – Wiktor Stribiżew Aug 31 '16 at 22:19
  • @WiktorStribiżew true, I'm just pointing out the difference between surrounding the pattern in quotes vs not. – VLAZ Aug 31 '16 at 22:21

1 Answers1

2

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);
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563