Search code examples
javascriptregexmatchstring-length

javascript how match whole words but in certain length limit


for example i have this two strings:

string1:

"hi sir may name is Jone"

string2

 "hi may name is Jone"

i have this this regex:

     var regex = XRegExp('hi(?:(?!hi|Jone).)*?Jone', 'gs');

will match both of them but i want to modify the regex to match only in limited length of the whole string

i want to match the string two "hi may name is Jone" as had less words length how to do it..


Solution

  • If you want to get the string with the least amount of words that also matches your regex, you could split and use a whitespace as a separator and check the length of the returned array.

    As an example with an array of strings, you could create var longestString = ""; which will at the end of the loop contain the shortest matched string.

    In the loop, first check if there is a match and if longestString is an empty string. If that is the case then set the variable so you have a match to compare against future possible matches.

    var strings = [
      "test",
      "hi sir may name is Jone",
      "hi may name is Jone",
      "hi Jone",
      "hi may name is Jone test",
      "hi i am Jone",
      "may name is Jone test",
      "hi may name is Jane test test 2"
    ];
    
    var regex = /hi(?:(?!hi|Jone).)*?Jone/;
    var longestString = "";
    
    strings.forEach((str) => {
      var match = XRegExp.match(str, regex);
      if (match && longestString === "") {
        longestString = str;
        return;
      }
      if (match && str.split(" ").length < longestString.split(" ").length) {
        longestString = str;
      }
    });
    console.log(longestString);
    <script src="https://unpkg.com/xregexp/xregexp-all.js"></script>