Partial matching a string against a regex

# Sassan Haradji (8 years ago)

Suppose that I have this regular expression: /abcd/ Suppose that I want to check the user input against that regex and disallow entering invalid characters in the input. When user inputs "ab", it fails as an match for the regex, but I can't disallow entering "a" and then "b" as user can't enter all 4 characters at once (except for copy/paste). So what I need here is a partial match which checks if an incomplete string can be potentially a match for a regex.

Java has something for this purpose: .hitEnd() (described here glaforge.appspot.com/article/incomplete-string-regex-matching) python doesn't do it natively but has this package that does the job: pypi.python.org/pypi/regex.

I didn't find any solution for it in js. It's been asked years ago: stackoverflow.com/questions/9060979/javascript-regex-partial-match and even before that: stackoverflow.com/questions/416425/check-if-string-is-a-prefix-of-a-javascript-regexp And I asked it here again: stackoverflow.com/questions/42461651/partial-matching-a-string-against-a-regex and still no answer.

I’ve created an issue requesting this feature on xregexp. But I think it’d be great if native js regex engine could handle this it.

# Kent C. Dodds (8 years ago)

I can't say that I know what the repercussions of such a feature would be, but I'll just add that I've definitely had this use case before and feel like it would be really useful to have in the language. 👍

# Michael J. Ryan (8 years ago)

I actually like the idea... You can do an optional matching block for parents (...)? But that would be patterns for each character... Having a String.startsWith that can do a match against the start of a rexexp would be cool. and/or regex.testStart

# Sassan Haradji (8 years ago)

This is the issue I created for XRegExp to support it: slevithan/xregexp#165, slevithan/xregexp#165

and this is an old issue about it again: slevithan/xregexp#52, slevithan/xregexp#52

They say it’s hard to implement it without accessing the internal regex mechanism.

Btw, in the stackoverflow thread I created and referenced in first email someone came with a good temporary solution that works for me. I hope we’ll have the complete version in future versions of js.