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.

2
  • 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. Commented Jan 25, 2012 at 15:26
  • Look at stackoverflow.com/questions/1789945/javascript-string-contains Commented Jan 25, 2012 at 15:41

4 Answers 4

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
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try this

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

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

Comments

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+

Comments

0

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

if(currentHoverOnItem.indexOf(myId) != -1)
{
    //Do something
}

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.