1

I have this Example 1:

myString = 'cdn.google.com/something.png';
console.log(myString.match(myString));

Everything works just fine, but when it comes to Example 2:

myString = 'cdn.google.com/something.png?231564';
console.log(myString.match(myString));

It returns the value of 'null'. I don't know what happened anymore.. I searched for the keywords 'a string does not Match itself' and found nothing. Can somebody help me? Thank you.

4 Answers4

2

The String#match method would treat the argument as a regex(by parsing if not), where . and ? has special meaning.

  1. . matches any character (except for line terminators)
  2. ? Quantifier — Matches between zero and one times, as many times as possible, giving back as needed

So . wouldn't cause any problem since . can be used to match any character except line but ? would since it's using to match zero or one-time occurrence of any character.

For eg: .png?23 => matches .png23 or .pn23


From MDN docs :

If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj).


It's better to use String#indexOf instead which returns the index in the string if found or returns -1 if not found.

console.log(myString.indexOf(myString) > -1);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0

match in Javascript compares a String against a RegEx. Luckily in your first example it works.

I guess you are looking for a method like localCompare.

Hope this helps!

Stuti Rastogi
  • 1,162
  • 2
  • 16
  • 26
0

match() search the string using a regular expression pattern.

So

var s = "My String";
s.match(/Regex Here/);

will try to match s for given regular expression .

In your example:-

myString = 'cdn.google.com/something.png'; // It will be treated as regex
console.log(myString.match(myString));

myString = 'cdn.google.com/something.png?231564';  // It will be treated as regex , result differ because of ? 
console.log(myString.match(myString));
Deepak Dixit
  • 1,510
  • 15
  • 24
0

You can escape the argument to match, however if you do that you could just use == to compare the strings. This post contains a regex string escape function:

How to escape regular expression in javascript?

RegExp.quote = function(str) {
    return (str+'').replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&");
};

It can be used like this:

myString = 'cdn.google.com/something.png?231564';
console.log(myString.match(RegExp.quote
(myString)));

If you want to match any number after the question mark, you could do it like this:

myString = 'cdn.google.com/something.png?';
console.log((myString+"18193819").match(RegExp.quote
(myString) + '\\d+'));
Community
  • 1
  • 1
Adder
  • 5,708
  • 1
  • 28
  • 56