Get Middle Chars
You are going to be given a word. Your job is to return the middle character of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters.
by Pranab Dey
HTML
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mocha/3.1.0/mocha.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/3.1.0/mocha.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/3.5.0/chai.min.js"></script>
<div style="padding: 10px; color: grey">
<h4>Problem:</h4>
<p>You are going to be given a word. Your job is to return the middle character of the word.
If the word's length is odd, return the middle character.
If the word's length is even, return the middle 2 characters.</p>
<p><strong>Sample Input:</strong> test</p>
<p><strong>Sample Output:</strong> es</p>
<br>
<p><strong>Sample Input:</strong> testing</p>
<p><strong>Sample Output:</strong> t</p>
</div>
<hr><br><br>
<div id="mocha"></div>
JavaScript
// Please note that you cannot edit HTML/CSS or include any libraries.
// You can use ES2016 (Babel) or ES5 to solve this problem:
function getMiddle(string) {
var str = string.length-1;
if(str%2 === 0){
return string[str/2];
}
else{
return string[Math.floor(str/2)] + string[Math.floor(str/2+1)];
}
}
// If your solution pass all tests, you should see a green tick for all test cases
// Don't edit below this line.
mocha.setup("bdd");
chai.should();
describe('Get Middle Chars', function(){
it('Test Case #1 - test', function(){
var output = getMiddle('test');
output.should.equal('es');
});
it('Test Case #2 - testing', function(){
var output = getMiddle('testing');
output.should.equal('t');
});
it('Test Case #3 - middle', function(){
var output = getMiddle('middle');
output.should.equal('dd');
});
});
mocha.run();