Home > Net >  Regex to match word and substrings
Regex to match word and substrings

Time:08-10

I have a list of commands a user can type into an HTML input element:

  • create
  • load
  • update
  • delete
  • draw

Currently I am setting the pattern attribute equal to:

^([Cc][Rr][Ee][Aa][Tt][Ee]|[Ll][Oo][Aa][Dd]|[Uu][Pp][Dd][Aa][Tt][Ee]|[Dd][Ee][Ll][Ee][Tt][Ee]|[Dd][Rr][Aa][Ww])$

From what I have read, HTML5 cannot use the case insensitive regex flag, so I had to bracket every letter [Cc] to create a case insensitive pattern. If the user types a word that doesn't match a word in the list, a validation statement will notify them.

I do not want the validation statement to pop up if the user has typed a set of characters that could become a list item. For example, if the user were attempting to run the create command, I would want "c", "cr", "cre", "crea", "creat", and "create" to all be valid entries.

How can I accomplish this with regex?

CodePudding user response:

I don't think you need a regular expression for that, you can use some method to loop throw an array of commands, and use startsWith method to check if there are any commands start with the input value, Also you can use toLowerCase() to ignore case sensitivity.

const commands = ['create', 'load', 'update', 'delete', 'draw']
let prevInputValue = ''

const input = document.querySelector('input');

input.addEventListener('input', (event) => {
    const value = event.target.value;
    const exist = commands.some(command => command.startsWith(value.toLowerCase()))
    
    if (!exist) {
        alert('Wrong Input');
        event.target.value = prevInputValue
    }
    prevInputValue = value;
})
<input type="text" />

  • Related