The regular expression in JS is the match of the whole word, with the exception of the optional s at the end

I am trying to write a regular expression that will match a word, but will not match s at the end, if there is one (to "de-pluralize" the word). I can't seem to get it to work.

The input format is always a number and then a word, for example:   1 carrot

I want to combine the word, but not with s at the end. Thus, it will be suitable carrotfor 1 carrotand 4 carrots.

I tried to see how, /\w+(?=s)/i but then it would not correspond to a singular word. I do not know how to make an β€œoptional look”, if that makes sense. Any help is much appreciated!

+4
source share
2 answers

You can use this lookahead regex:

/\b\w+?(?=s?$)/m

RegEx Demo

(?=s?$)will state the presence of an optional sinput end anchor $>

+2
source

Plus makes your match greedy, you want it lazy .

\w+?(?=s)
+1
source

Source: https://habr.com/ru/post/1620185/


All Articles