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

6
  • Remove the single quotes, as you're splitting on a string rather than a pattern. Commented Aug 31, 2016 at 22:15
  • @Trey: Not only. The dot must be escaped, too. OP is not sure whether it must be escaped or not. Commented Aug 31, 2016 at 22:16
  • @WiktorStribiżew correct, but he has escaped them in some of his attempts so I didn't mention it Commented Aug 31, 2016 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. Commented Aug 31, 2016 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. Commented Aug 31, 2016 at 22:19

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.