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 = promp开发者_高级运维t('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>
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.
Instead of /ie/
, use /ie$/
. That will only match strings that end with ie
.
精彩评论