Get the first character of string JavaScript | example code

The simplest way to get the first character of the given string in JavaScript is the charAt method. This method returns the character at the specified index in a string. Another way is the substring method to extracts the characters from a string, between two specified indices.

Get the first character of string JavaScript Examples

HTML example codes:-

Using charAt() method

The index of the first character is 0, the second character is 1, and so on.

<!DOCTYPE HTML> 
<html> 

<body> 

	<script>
		var str = "HELLO WORLD";
		var res = str.charAt(0); 

		alert(res);

	</script> 
</body> 
</html>	

Using substring Method

This method will returns the new sub string. Pass the index value 0 to 1 to get first char.

<!DOCTYPE HTML> 
<html> 

<body> 

	<script>
		var str = "HELLO WORLD";
		var res = str.substring(0, 1); 

		alert(res);

	</script> 
</body> 
</html>	

Output: Result will be same for both examples because of given string first character is same.

Get the first character of string JavaScript

Do CommNet if you have any doubts and suggestions on this basic JS topic

Note: All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.