Regex - check if input still has chances to become matching

前端 未结 11 1434
天命终不由人
天命终不由人 2020-12-05 00:51

We\'ve got such regexp:

var regexp = /^one (two)+ three/;

So only string like \"one two three\" or \"one two three four\

11条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-05 01:11

    Your original question was simply testing a string's placement within another, specifically, the start. The fastest way to do that would be to use substr on the match string, followed by indexOf. I've updated my original answer to reflect that:

    function check(str){
      return 'one two three'.substr(0, str.length) === str;
    };
    console.log(check('one'));           // true
    console.log(check('one two'));       // true
    console.log(check('one two three')); // true
    console.log(check('one three'));     // false
    

    If you need case-insensitivity, it's still fastest to simply toLowerCase the match & input strings. (If interested, here's a jsperf of substr, indexOf and RegExp testing for the start of a string, case-insensitively: http://jsperf.com/substr-vs-indexof-vs-regex )

提交回复
热议问题