user779159
user779159

Reputation: 9602

How to match a JS regexp that may or may not have a suffix

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 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

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

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

Related Questions