Click here to Skip to main content
15,867,308 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Write a function called charAt which accepts a string and an index (number) and returns the character at that index.

The function should return an empty string if the number is greater than the length of the string.

Can't use the built in charAt method

examples:

// will give 'e'
charAt('awesome', 2)

// will give ''
charAt('awesome', 12)

What I have tried:

function charAt(string, index) {
var charAt = Array.from(string)[index];
return charAt;
}
Posted
Updated 2-May-20 6:13am
Comments
phil.o 28-Apr-20 16:22pm    
And what is your question?
Pseudocode01 28-Apr-20 16:33pm    
Basically want to know if I'm doing it right, based on the given parameters for the practice problem.
Completely new to JS here....
ZurdoDev 28-Apr-20 16:36pm    
Do you get the right answer?
Pseudocode01 28-Apr-20 16:37pm    
Unfortunately no, keeps returning characters at an index or empty string. I've looked all over google too, this should be correct.
Richard MacCutchan 29-Apr-20 4:31am    
You need to check the value of the index. If it is less than zero, or equal or greater than the string length, then it is not valid.

Quote:
Unfortunately no, keeps returning characters at an index or empty string. I've looked all over google too, this should be correct.


So start by checking what you are passing to it, and how - use either JSFiddle or w3schools to build a "framework" for it, and test it:
JavaScript
alert(charAt('awesome', 2));

alert(charAt('awesome', 12));

function charAt(string, index) {
var charAt = Array.from(string)[index];
return charAt;
}

It doesn't do exactly what you are asked for in both cases, but that's because you haven't checked for it ...
 
Share this answer
 
Here's the model solution
function charAt(str, idx) {
return idx < str.length ? str[idx] : '';
}

I just added an if and an else statement and I passed. I don't think this code actually works, but it got me past the repl.it
let a="win";
let i= 1;
function charAt(a,i){
var charAt = Array.from(a)[i];
if (i<3&&i>=0){
return charAt;
}
else{
return ""
}
}
console.log(charAt)
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900