-2

I want regular expression which return true if any continuous three charters match. For e.g /[money]{3,}/g It return true for mon, one, ney and return false for mny.

Tushar
  • 78,625
  • 15
  • 134
  • 154
Ritesh Tiwari
  • 89
  • 1
  • 3

2 Answers2

0

I would not use regex, why not use indexOf, it's less code and better to read.

something like "money".indexOf("mon")>-1

Here a Demo, with all listed examples:

let values = ["mon","one", "ney", "mny"];
let shouldMatch = "money";

for (let idx = 0; idx<values.length;idx++){
    console.info(values[idx], "=", shouldMatch.indexOf(values[idx])>-1);
}

But If you want to use RegExp, you could use it like this:
(BTW: this is only a "fancy" way to write the example above)

let values = ["mon","one", "ney", "mny"];


function matcher(word, value){
    return (new RegExp(value)).test(word);
}

for (let idx = 0; idx<values.length;idx++){
    console.info(values[idx], "=", matcher("money", values[idx]));
}

The Code Basically:

Creates a new Regular Expression exp. (new RegExp("mon")) (equal to /mon/) and than just testing, if the "pattern" matches the word "money" (new RegExp("mon")).test("money") this returns true.

Here it is all turned around, we are checking if money fits into the (sub)-pattern mon.

Community
  • 1
  • 1
winner_joiner
  • 3,643
  • 4
  • 32
  • 48
0

Regular expressions function as a search for a character string, your application would require taking a base string and dynamically building an insane regex with many ORs and lookaheads/behinds. For your application, write a function that uses indexOf

function stringContainsSubstr(sourceStr, subStr) {
  return sourceStr.indexOf(subStr) !== -1;
}

var exampleStrs = ["mon", "one", "ney", "mny"];
var str = "money";

for (var i = 0; i < exampleStrs.length; i++) {
  console.log(stringContainsSubstr(str, exampleStrs[i]));
}

http://plnkr.co/edit/2mtV1NeD1MYta5v49oWr

ryanlutgen
  • 2,681
  • 1
  • 18
  • 29