Check if string is a prefix of a Javascript RegExp

后端 未结 5 2125
旧巷少年郎
旧巷少年郎 2021-01-04 03:31

In Javascript I have defined a regular expression and now a user is typing in a string. I want to tell him if his string still could match the RegExp if he continues typing

5条回答
  •  庸人自扰
    2021-01-04 04:18

    One way of doing this could be to hook to the onKeyUp event of a text box and .test the text against the regular expression. My assumption is of course that you want to do a regular expression matching. I'm not sure if this is exactly what you need, in fact your code:

    "a".isPrefixOf( re ); // true
    

    will never match since it's required to also have a subsequent "b" character (you may want to modify the regular expression). For instance, this code will test against any string matching this format:

    a-n(n)-b
    

    Here is the code, save it as a page and load it in your browser:

    
    
    
        
        

提交回复
热议问题