-1

I'd like to match a string that containing mandatory words or words sequences with repetitions. I even don't know if I can do that with a Regexp.

Example string

No depending be convinced in unfeeling he. 
Excellence she unaffected and too sentiments her. 
Rooms he doors there ye aware in by shall. 
Education remainder in so cordially. 
His remainder and own dejection daughters sportsmen. 
Is easy took he shed to kind.  

Mandatory words

Rooms (1x)
Excellence (2x)
Education (1x)
House (1x)

Should return something like

Success: false

Rooms: 1
Excellence: 1
Education: 1
House: 0

Thanks for support

bln
  • 310
  • 1
  • 5

2 Answers2

1

You could do something like this:

var requiredWords = {
  Rooms: 1,
  Excellence: 2,
  Education: 1,
  House: 1,
};

var success = true;
for(var word in requiredWords){
  var requiredAmount = requiredWords[word];

  //create and check against regex
  var regex = new RegExp(word, 'g');
  var count = (yourString.match(regex) || []).length;

  //if it doesn't occur often enough, the string is not ok
  if(count < requiredAmount){
    success = false;
  }
}

alert(success);

You create an object with all required words an the needed amount, then loop through them and check if they occur often enough. If not a single word fails, the string is OK.

jsFiddle

Michael Kunst
  • 2,978
  • 25
  • 40
  • Hey thanks that's what exactly what i was coding right now! Thanks for your time – bln Mar 01 '17 at 12:56
  • can I ask you smtg else? If I have 2 mandatory "strings" like - my name - name and a sentence like 'my name is john' How can I be sure to only match 'my name' and not 'name' in this case? – bln Mar 01 '17 at 13:15
1

The solution using String.prototype.match() and Array.prototype.reduce() functions:

function checkMandatoryWords(str, wordSet) {
    var result = Object.keys(wordSet).reduce(function (r, k) {
        var m = str.match(new RegExp('\\b' + k + '\\b', 'g'));
        r[k] = m? m.length : 0; // writing the number of occurrences
        if (m && m.length !== wordSet[k]) r.Success = false;

        return r;
    }, {Success: true});

    return result;
}

var str = "No depending be convinced in unfeeling he. \
Excellence she unaffected and too sentiments her.\
    Rooms he doors there ye aware in by shall.\
    Education remainder in so cordially.\
    His remainder and own dejection daughters sportsmen.\
    Is easy took he shed to kind.  ",

    wordSet = {Rooms: 1, Excellence: 2, Education: 1, House: 1};

console.log(checkMandatoryWords(str, wordSet));
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105