0

Can someone explain why this does not work? (I am using Chrome Developer Console)

pattern  
-> "/Xmp\.MP\.RegionInfo\/MPRI:Regions/"
key
-> "Xmp.MP.RegionInfo/MPRI:Regions[1]"
key.search(pattern)
-> -1
key.search(/Xmp\.MP\.RegionInfo\/MPRI:Regions/)
-> -1
"Xmp.MP.RegionInfo/MPRI:Regions[1]".search(pat)
-> -1
"Xmp.MP.RegionInfo/MPRI:Regions[1]".search(/Xmp\.MP\.RegionInfo\/MPRI:Regions/)
-> 0

It make absolutely no sense to me that the search does not match if i use the variables....

1
  • I can't reproduce this behavior: key.search(/Xmp\.MP\.RegionInfo\/MPRI:Regions/) outputs -1. I get 0 instead, as is expected. Commented Nov 20, 2012 at 11:13

3 Answers 3

2

It looks like pattern is a String in your first example, it needs to be a RegExp object:

var pattern = /Xmp\.MP\.RegionInfo\/MPRI:Regions/
var key = "Xmp.MP.RegionInfo/MPRI:Regions[1]"

key.search(pattern); // equals 0

If you want to convert a string to a regex, use the RegExp constructor (but remove the slashes):

var pattern = new RegExp("Xmp\.MP\.RegionInfo\/MPRI:Regions");

http://jsfiddle.net/CpEjA/

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

1 Comment

No it doesn't, but it is in the question. Can't explain it.
0

In your example pattern appears to be a string. You need it to be a RegExp object.

Comments

0

In first case your pattern is wrapped in quotes, so it is string. In second case it is without quotes -> it is RegExp object.

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.