JavaScript | Get The Position Of Character In A String

          We are going to use “string.indexOf()” method to get the position of a character in the given string. The above syntax can also be used to check whether a character is present in the given string. The “string.indexOf()” method return’s the position f the first matching character. If the character is not found in the given string, it returns “-1” and thus we can use this syntax to check whether a character is present in the given string. Let’s move on to the function.

function check() {
 var str=”this is an example string”;
 var index=str.indexOf(‘e’);
 var result;
 if( index == -1 ) {
  result=”Character Not Present”;
 }
 result=”Character’s Index: “+index;
 return result;
}
          In the above function I have assumed a string and checked for the character “e”. You can pass the string and character through the parameter’s for your convenience.

Note: JavaScript is case sensitive. Take care while using the syntax.

Leave a Reply

Your email address will not be published. Required fields are marked *