Reputation: 9602
I'm trying to make a JS regex that returns example
in all of these input strings, which may have question marks in them.
example?after?after
example?after
example?
example
example
would be a dynamic string so I can't literally match the string 'example'.
'example?after?after'.match(/(.*?)\?/)[1]
'example?after'.match(/(.*?)\?/)[1]
'example?'.match(/(.*?)\?/)[1]
'example'.match(/(.*?)\?/)[1]
The first 3 above return example
as expected but the last one gives an error. How can I modify the regex to return the expected result?
Upvotes: 1
Views: 86
Reputation: 626927
You may use
/^[^?]+/
See the regex demo
The ^
matches the start of string and [^?]+
matches one or more symbols other than ?
.
var regex = /^[^?]+/;
var strs =[ 'example?after?after', 'example?after', 'example?', 'example'];
for (var s of strs)
{
console.log(s + " => " + s.match(regex));
}
Upvotes: 3