victormejia
victormejia

Reputation: 1184

javascript regex: match all words with just some letters

So I'm fairly new to regular expressions. Any help is appreciated.

I have a string in the following format:

var str: ".item-61347 .item-79134 .item-79465 .item-96464"

I want to be able to extract all matching words, given just some input. For example:

input: 13 --> .item-61347 .item-79134
input: 79 --> .item-79134 .item-79465
input: 96464 --> .item-96464

The input will be a string variable, so ideally I would like to be able to do something like this:

str.match(<regexp with string containing input>)

Upvotes: 0

Views: 878

Answers (2)

Esailija
Esailija

Reputation: 140210

Doesn't look like there is need for a regexp at all:

var items = ".item-61347 .item-79134 .item-79465 .item-96464".split(" ");

var itemsThatMatch13 = items.filter( function(v) {
    return v.indexOf("13") > 0;
});

//[".item-61347", ".item-79134"]

Upvotes: 4

raina77ow
raina77ow

Reputation: 106375

How about this:

var testRegex, 
    testInputs = [13, 79, 96464];
var testStr   = '.item-61347 .item-79134 .item-79465 .item-96464';
for (var i = 0, l = testInputs.length; i < l; ++i) {
    testRegex = new RegExp('[.]item-(?=[0-9]*' + testInputs[i] + ')[0-9]+', 'ig');
    console.log(testStr.match(testRegex));
}

The point is using lookaheads in your regex to simultaneously check the digits subpattern and your input in it.

Upvotes: 2

Related Questions