1

say i have the following variables:

myId; //Email_PDF
currentHoverOnItem; //Email_PDF_english of Email_PDF_Dutch or ...

So the first value is "Email_PDF" and the second is "Email_PDF_english". What i want i when currentHoverOnItem contains myId, then something can be executed. This is what i have so far:

var pattern = new RegExp("^/"+myId+"/$");

if (currentHoverOnItem.match(pattern))
{
    //Do something
}

Is this the right way to use the regex? It should match part of the string, there can be text before or after the match.

vincent
  • 1,243
  • 4
  • 15
  • 29
  • Providing that currentHoverOnItem returns a string then there is nothing wrong with what you are doing. Except the $ in the pattern means that you won't get a match with values you have given in the example. – Dan Iveson Jan 25 '12 at 15:26
  • Look at http://stackoverflow.com/questions/1789945/javascript-string-contains – hop Jan 25 '12 at 15:41

4 Answers4

1

Is this the right way to use the regex?

No! Regexes are for patterns, not for literal strings. Use indexOf

if (currentHoverOnItem.indexOf(myId) >= 0)
{
    //Do something
}
georg
  • 211,518
  • 52
  • 313
  • 390
0

Try this

var pattern = new RegExp(myId, "g");

if (currentHoverOnItem.match(pattern))
{
    //Do something
}
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
0

Your pattern is "anchored", meaning that ^ and $ specifiy begin and end of your string. To match "Email_PDF_english" in an anchored pattern you could use ^Email_PDF_(.*)$, but it won't match if your string is longer, as your comment suggests.

If it's not anchored you could test for a blank following the Email_PDF_... string, ie Email_PDF_([^\s]*)\s+

ExternalUse
  • 2,053
  • 2
  • 25
  • 37
0

You need not use a reg_exp here. Using indexOf will do the trick for you

if(currentHoverOnItem.indexOf(myId) != -1)
{
    //Do something
}
hop
  • 2,518
  • 11
  • 40
  • 56