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 extract 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 return the new sub-string. Pass the index value 0 to 1 to get the first char.

<!DOCTYPE HTML> 
<html> 

<body> 

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

		alert(res);

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

Output: The result will be the same for both examples because of given string’s first character is the same.

Get the first character of string JavaScript

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

Note: The 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.