简体   繁体   中英

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>

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM