Skip to content

Get first n characters of string JavaScript | Example code

  • by

You can use the substring or slice method to Get the first n characters of a string in JavaScript. Where n could be any number 1,2,3… so on.

Get first n characters of string JavaScript Examples

HTML examples code: Let’s get the first 4 char from a string in JS.

Using substring() Method:

<!DOCTYPE HTML> 
<html> 
 
<body> 
 
	<script>
		var str = "HELLO WORLD";
		var res = str.substring(0, 4); 
 
		alert(res);
 
	</script> 
</body> 
</html>	

Using slice() Method:

<!DOCTYPE HTML> 
<html> 
 
<body> 
 
	<script>
		var str = "HELLO WORLD";
		var res = str.slice(0,4);
 
		alert(res);
 
	</script> 
</body> 
</html>	

Output: Result will be the same because the given string and get number char length is the same.

Get first n characters of string JavaScript

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

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