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 ch
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>
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,
function getIndex(text, i) {
return text.slice(i,i+1);
}
console.log(getIndex('great', 1)); // --> r
Create the function as below:
function getIndex(input, i) {
return input.substring(i, i+1);
}
getIndex("great", 1)
I hope that helps!