简体   繁体   中英

How Search for a String in an array using javascript without using regular expressions

I'm a newbie to Javascript please help me to solve my problem

function myFunction() {
var fr = ["banana", "orange", "apple", "mango"];
var n = fr.length;
var s = "a";
for(i=0;i<n;i++){
  if(fr[i].indexOf(s) != -1){
     console.log(fr[i]);          
  }
 }        
}

and the output im getting is

banana
orange
apple
mango

but what i want is that it should print only the word that starts with the given letter/word

i.e., : apple 

When you are checking index!=-1 , that is basically you are checking that a is present anywhere in string.

If you want to check that string start with a you should check if a is at 0th index.

Check this in if condition

if(fr[i].indexOf(s) === 0)

This will give the expected output.

The reason that all of them are showing is because all of those strings contain the character 'a'. If you only want to show the strings that begin the the character 'a' Mritunjay's solution is the way to go

You can use substring. This example will give you the first letter in the string.

 if(fr[i].indexOf(s) != -1){
     if(fr[i].substring(1, 0) === "b")
     {
         console.log("b found");
     }
 }

(For the record) Case insensitive filtering of your array on /^a/i (see MDN )

["banana", "orange", "apple", "mango"]
  .filter( function (v) { return v[0].toLowerCase() === 'a'; } );

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