How to compare two sentences by considering the space only in dynamic portion?

Viewed 85

I need to compare two sentences. First one is defined in a database like below.

var text1 = "Dear {#dynamic#} {#dynamic#} Welcome to MAX private ltd"

Then the text which comes from customer is given below.

"var text2 = "Dear joe harry Welcome to MAX private ltd"

Here in place of dynamic there could be any value that customer can substitute and send as an input ( 0- 10) is the character limit for dynamic content.

I need to compare both the sentences and return the response. Problem here is, we should not consider spaces in the other portion of the sentence except for dynamic part. For example,

   "var text3 = "Dear joe harry Welcome to MA Xprivatel td"

While comparing text1 with text3 , it should be valid even though we have spaces near the MA Xprivatel td". But for dynamic portion , if {#dynamic#}{#dynamic#} comes continuously, it can be 20 characters max including spaces. If two {#dynamic#} {#dynamic#} with spaces, max character limit can be 21 including spaces.

My current code is below,

   text1 = text1.replace(/(^|.)\s($|.)/g, (x, g1, g2) => (x == "} {" ? "}\\s+{" : g1 + "\\s\*" + g2));
   var separators_regex = /{#dynamic#}|((\s\*))/gi;
   text1= text1.replace(separators_regex, (x, y) => y ? y : ".{0,10}"); 
   let regex1 = RegExp("^" + text1+ "$", "i");
   if (!regex1.test(text2)) {  // or regex1.test(text3)
        Status = "Fail"  
    }
 

Whatever I try, at some scenario it is failing. The above code is failing for text3. Im stuck with these for too long. Can anybody please help me with this?

1 Answers

You can use

var text2 = "Dear 1234567890 12345678901 Welcome to MAX private ltd"
var text1s = ["Dear {#dynamic#} {#dynamic#} Welcome to MAX private ltd {#dynamic#}"];
var text2 = "Dear joe harry Welcome to MAX private ltd";
for (var text1 of text1s) {
  var rx = new RegExp(text1.replace(/\s*(\{#dynamic#}(?:\s*\{#dynamic#})*)/g, (x, y) =>
    '\\s*.{0,' + ((y.match(/\{#dynamic#}/g) || ['']).length * 10 + (y.match(/\s/g) || '').length) + '}'))
  console.log(rx)
  console.log(rx.test(text2))  
}

This means:

  • Sequences of possibly whitespace-separated {#dynamic#} chunks are replaced with the necessary .{0,x} patterns
  • If there are spaces in between, these are added up to x
  • If there are leading whitesapces, they will be made optional, \s* will replace any amount of whitespaces.
Related