How do I convert this php code to javascript?

-1
<!DOCTYPE html>

<html>


<head>
    <meta charset="utf-8">
    <title> text4  </title>

</head>
<body>

    <?php
/**
 * Converte uma palavra no plural para o singular
 * @param string $str Uma palavra
 * @return string Palavra no singular
 */
function pluraltosingular($str) {
    if (substr($str, -1) != 's')
        return $str;
    // albuns batons marrons
    if (substr($str, -2, 1) == 'n')
        return substr($str, 0, -2) . 'm';
    // flores gizes vezes tenis
    else if (strpos('aeou', substr($str, 0, 1)) === false && substr($str, -2, 1) == 'e' && strpos('nrsz', substr($str, -3, 1)) !== false)
        return substr($str, 0, -2);
    // aneis anzois jornais
    else if (substr($str, -2) == 'is' && strpos('aeiou', substr($str, -3, 1)) !== false)
        return substr($str, 0, -2) . 'l';
    // frances portugues
    else if (substr($str, -2) == 'es' && strpos('clu', substr($str, -3, 1)) !== false)
        return $str;
    // caes paes
    else if (substr($str, -3) == 'aes')
        return substr($str, 0, -2) . 'o';
    // leoes
    else if (substr($str, -3) == 'oes')
        return substr($str, 0, -3) . 'ao';
    // exceto onibus lapis tenis arvores
    else if (strpos('ius', substr($str, -2, 1)) === false && substr($str, -3, 1) != 'n')
        return substr($str, 0, -1);
    return $str;
}
?>



    </body>

</html>
    
asked by anonymous 18.04.2017 / 18:11

2 answers

4

Use the corresponding functions

PHP substr > JavaScript substr

PHP strpos > JavaScript indexOf

PHP operator. > Javascript operator +

The structure of IF and logical operators are the same.

    
18.04.2017 / 18:58
0

I made an example for you to see how it does .. Now just follow the same line ..

alert(pluraltosingular("flores"));
function pluraltosingular($str) {
    if ($str.substr($str.length - 1) != 's')
        return $str;
    // albuns batons marrons
    if ($str.substr($str.length - 2,1) == 'n')
        return $str.substr(0,$str.length - 2) + 'm';
    // flores gizes vezes tenis
    else if('aeou'.indexOf($str.substr(0,1)) == -1 && $str.substr($str.length - 2,1) == 'e' && 'nrsz'.indexOf($str.substr($str.length - 3,1)) != -1)
    return $str.substr(0,$str.length - 2)
    /*
    // aneis anzois jornais
    else if (substr($str, -2) == 'is' && strpos('aeiou', substr($str, -3, 1)) !== false)
        return substr($str, 0, -2) . 'l';
    // frances portugues
    else if (substr($str, -2) == 'es' && strpos('clu', substr($str, -3, 1)) !== false)
        return $str;
    // caes paes
    else if (substr($str, -3) == 'aes')
        return substr($str, 0, -2) . 'o';
    // leoes
    else if (substr($str, -3) == 'oes')
        return substr($str, 0, -3) . 'ao';
    // exceto onibus lapis tenis arvores
    else if (strpos('ius', substr($str, -2, 1)) === false && substr($str, -3, 1) != 'n')
        return substr($str, 0, -1);*/
    return $str;
}
    
18.04.2017 / 19:02