How to find a character in a string in JavaScript

{0 Comments}

There are two methods which is much more widely used in JavaScript to finding some character or part of string. This is CharAt and indexOF.

CharAT

CharAT is JavaScript method which will help you to get the character at particular position like at first, or eight places.  Thing to remember that here count starts from zero not form the one. To use to call the charAT method we uses famous dot operator which is used every where. In this method accepts a parameter which is the number of position and then it will return the char which is at the passed position.  Following is the implementation of the same method to find the character at following position.

 Javascript |  copy code |? 
1
var str = "HELLO WORLD";
2
var n = str.charAt(2)
3

Index OF

This is just the opposite method of CharAT which will find the position of the character or the position of the substring. In this method also the thing which we should remember that, here also the count start with zero not from the one. If string which you try to find is not present then it will return -1.

 Javascript |  copy code |? 
1
var str="Hello world";
2
 
3
        var n=str.indexOf("world");
4
 
5
        alert(n);
6

        

Leave a Comment

Your email address will not be published.