JavaScript- How do I return the character at that index without using charAt method

I have a function that accept two parameters string and index. How do I write a code that will return the character at that index without using javascript built in method charAt. for e.g getIndex(great, 1) should return r

Answers:

Answer

Something like this should work for you:

getIndex = (str, index) => str.split('')[index];
console.log(getIndex("foobar", 3));

This may also be of interest:

String.prototype.getIndex = function(idx) {
  return this.split('')[idx];
}
console.log("foobar".getIndex(3));

Hope this helps,

Answer

Create the function as below:

function getIndex(input, i) {
    return input.substring(i, i+1);
}

getIndex("great", 1)

I hope that helps!

Answer

Can you please check this:

$('#show').click(function(){
  var string = $('#string').html();
  var position = $('#position').val() - 1;
  var result = string[position];
  $('#result').html(result);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<span id='string'>ABCDEFGHIJKLMNOPQRSTUVWXYZ</span><br/>
<input type='text' id='position' value='5'> = 
<span id="result"></span>
<br/>
<button id='show'>DISPLAY RESULT</button>

Answer
    function getIndex(text, i) {
        return text.slice(i,i+1);
    }

    console.log(getIndex('great', 1));  // --> r

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.