Skip to content

Get the first two characters of string JavaScript | Example code

  • by

Get first two characters of string JavaScript HTML example code

You can use the inbuilt slice method to get the first 2 characters of a string in JavaScript.

Pass index value 0 for start and 1 for the end.

<!DOCTYPE HTML> 
<html> 

<body> 

	<script>
		var str = "Hello world, Simple example";
		
		var strFirst2 = str.substring(0,2);

		alert(strFirst2);
	</script>
</body> 
</html>	

Output:

Get the first two characters of string JavaScript

Do comment if you have any doubts and suggestions on this JS char 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

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