Skip to content

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

  • by

Use the substring method to split a string at the index in JavaScript. You can also create a 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 the 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 the match method and Regular expression to split the 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: 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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading