Get first n characters of string JavaScript | Example code

You can use substring or slice method to Get first n characters of 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 first 4 char from 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 same because given string and get number char length is same.

Get first n characters of string JavaScript

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

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