-1

Possible Duplicate:
Using a string variable as regular expression

I have a var that contains all English words. I want to use regular exp in order to filter the words according to specific letter that are stored in a var.

 var letter1 = "a";
    var letter2 = "b";
var words= "aardvark aardwolf aaron aback abacus abaft abalone abandon abandoned abandonment abandons abase abased abasement abash abashed abate abated abatement abates abattoir";

I tried this in order to find all the words that have the letter "a" and "b", but it is not working:

document.writeln(words.match(/letter1 +/ + letter2 +/g));
3
  • 2
    Your intent is not quite clear. What exactly do you want to get? All the words containing letter1 and letter2 at the same time? Commented Mar 24, 2012 at 8:04
  • 2
    Provide 1. Expected result, 2. Actual Result, 3. Code Commented Mar 24, 2012 at 8:06
  • <script type="text/javascript"> var abc = ["asdf","asfdf","sdgsdwvc","avdvcccv","acbfd","sdfsd","gvvfvbb","sdfge34"]; var pattern = /.*[ab].*/i; var res; for(a in abc) { res = abc[a].match(pattern); if(res!=null || res!=undefined) alert(res); } </script> Commented Mar 24, 2012 at 8:26

2 Answers 2

3

this pattern should do it:

/\S*[ab]\S*/g

and so

var pattern = new RegExp('\S*['+letter1+'|'+letter2+']\S*','g');
var matches = words.match(pattern);
document.writeln(matches);
Sign up to request clarification or add additional context in comments.

1 Comment

I need to find the whole word not only the two letters
0
>>> "acadfb".match(/a.*b|b.*a/)
["acadfb"]
>>> "basdfc".match(/a.*b|b.*a/)
["ba"]
>>> "asdfbasdfcvb".match(/a.*b|b.*a/)
["asdfbasdfcvb"]
>>> "cadsfg".match(/a.*b|b.*a/)


var myStringArray = ["Hello","World","asdfsadf","asdbc","cdjfieab"];
for (var i = 0; i < myStringArray.length; i++) {
   if(myStringArray[i].match(/a.*b|b.*a/)){
    console.log(myStringArray[i]);
   };
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.