Jojo
Jojo

Reputation: 81

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

Upvotes: 0

Views: 813

Answers (4)

Steve
Steve

Reputation: 395

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

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

Upvotes: 0

harsh pamnani
harsh pamnani

Reputation: 1756

Create the function as below:

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

getIndex("great", 1)

I hope that helps!

Upvotes: 1

Miroslav Glamuzina
Miroslav Glamuzina

Reputation: 4557

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,

Upvotes: 0

kapitan
kapitan

Reputation: 2212

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>

Upvotes: 0

Related Questions