JavaScript split a string at the index | Particular and nth position example

Use substring method to split a string at the index in JavaScript. You can also create function for it.

JavaScript split the string at index Example code

HTML example code: How do split a string at a particular index? e.g split string at index 10, making the string now equal to everything up to index 10, and then dumping the remainder.

<!DOCTYPE HTML> 
<html> 

<body> 

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

		var remainder = str.substring(10);

		console.log(sub);
		console.log(remainder);

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

Output:

JavaScript split a string at the index

Split string by comma

Let’s split string by comma at given index.

<script>
		var str = "Hello world, Simple example";
		
		function split_at_index(value, index)
		{
			return value.substring(0, index) + "," + value.substring(index);
		}

		console.log(split_at_index(str, 2));

	</script> 

How to Split a string at every nth position in JavaScript?

Answer: Use match method and Regular expression to split string at every given position in JS.

In the example splitting string after every 3rd index.

<!DOCTYPE HTML> 
<html> 

<body> 

	<script>
		var str = "foo faa foofaa foofaafoofaafoo faa";
		
		console.log(str.match(/.{1,3}/g) );

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

Output:

Split a string at every nth position in JavaScript

Do comment if you have any questions on this JS strings 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.