Get the middle character JavaScript | Extracting middle of a string example

Get the middle character JavaScript Example code:

Let’s Create a function that returns the middle character/s of a sentence.

<!DOCTYPE HTML> 
<html> 

<body> 

	<script>
		var str = "This is an simple sentence.";
		function extractMiddle(str) {

			var position;
			var length;

			if(str.length % 2 == 1) {
				position = str.length / 2;
				length = 1;
			} else {
				position = str.length / 2 - 1;
				length = 2;
			}

			return str.substring(position, position + length)
		}

		console.log(extractMiddle(str));

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

Output:

Get the middle character JavaScript

Do comment if you have any doubts and suggestions on this example code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version


One thought on “Get the middle character JavaScript | Extracting middle of a string example

  1. ‘use strict’
    let str = ‘This is an simple sentence.’;
    const extractMiddleLetter = (input) =>{
    if(input.length%2===0) return ‘No middle letter found’
    return input[Math.floor(input.length/2)]
    }
    console.log(extractMiddleLetter(str))

Leave a Reply

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