Drew Bartlett
Drew Bartlett

Reputation: 1891

How to search for words ending in a particular string?

I have basic JavaScript code that needs to tell how many names out of 5 end in i or l'. I have the code to tell how many contain an ly or i, just not ONLY at the end.

<script type="text/javascript">
    var names = new Array(5);
    var name;

    function start_user_prompt() {
        for(i=0;i<5;i++) {
            name = prompt('Enter name '+(i+1));
            names[i] = name;
        }   
        e_names(names);
    }       
    function e_names(names) {
        var name_count = 0;
        for(var i in names) { 
            // this needs to be changed to search it correctly
            if((names[i].search(/ie/) > 0) || names[i].search(/y/) > 0) {
                name_count++;
            }
        }
        document.write('The number of special names is : '+name_count);
    } 
</script>

Upvotes: 0

Views: 1788

Answers (2)

Ryan Mitchell
Ryan Mitchell

Reputation: 1410

Instead of /ie/, use /ie$/. That will only match strings that end with ie.

Upvotes: 3

Jakub Hampl
Jakub Hampl

Reputation: 40533

The $ in a regexp means end of string. So your regexps should be /ie$/ and /y$/.

You can simplify further with using only one regexp /(ie|y)$/. The | is an OR so it will match strings ending with ie or y.

Upvotes: 3

Related Questions