1

I am trying to catch all words that contains "centimeters", like: 10.50centimeters from this sentence "This product have 10.50centimeters length..".

my function:

function findMatchingWords(t, s) {
    var re = new RegExp("\\w*"+s+"\\w*", "g");
    return t.match(re);
}
findMatchingWords('This product have 10.50centimeters length..','centimeters');

but returns only "50centimeters". Is not getting the numbers before the dot.

Any help with this please?

Adrian
  • 491
  • 6
  • 23

1 Answers1

3

Is not getting the numbers before the dot.

\w doesn't match a dot, it's equivalent to [A-Za-z0-9_]. [\w.] would (or [A-Za-z0-9_.]).

var re = new RegExp("[\\w.]*"+s+"\\w*", "g");

Live Example:

function findMatchingWords(t, s) {
        var re = new RegExp("[\\w.]*"+s+"\\w*", "g");

    return t.match(re);
}
console.log(findMatchingWords('This product have 10.50centimeters length..','centimeters'));

Side note: You'll want to escape characters with special meaning in s before feeding it to the RegExp constructor. This question's answers have functions to do that.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875