Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - Make a word singular (singularize)

Tags:

javascript

I am currently seeking a way to "singularize" English words. I have found ways to do the opposite. Here's what I've come up with so far:

function singularize(word) {
  const endings = {
    ves: 'fe',
    ies: 'y',
    i: 'us',
    zes: '',
    ses: '',
    es: '',
    s: ''
  };
  return word.replace(
    new RegExp(`(${Object.keys(endings).join('|')})$`), 
    r => endings[r]
  );
}

However, this is not working in many cases (e.g. analysis – analyses, phenomenon – phenomena, series – series). Is there a more accurate way to do this without embedding a whole dictionary? Is there a way to access the dictionary of the browser?

And if there is no way without a dictionary, what would be at least a slightly more accurate solution?

like image 679
Julius Avatar asked May 23 '26 18:05

Julius


1 Answers

I think everything in your code is great.

But a small error not in the code but instead it's in the object of endings you have.

This is the code after editing the endings object and with some test cases:

function singularize(word) {
    const endings = {
        ves: 'fe',
        ies: 'y',
        i: 'us',
        zes: 'ze',
        ses: 's',
        es: 'e',
        s: ''
    };
    return word.replace(
        new RegExp(`(${Object.keys(endings).join('|')})$`), 
        r => endings[r]
    );
}

console.log(singularize("papers"))
console.log(singularize("strategies"))
console.log(singularize("lives"))
console.log(singularize("games"))
console.log(singularize("cacti"))
console.log(singularize("dozes"))

But the functionality of your code is done.

like image 70
Ahmed M. Zanaty Avatar answered May 26 '26 09:05

Ahmed M. Zanaty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!