1

Is there a way to get a certain letter from a value inside of an array?

For example, if my array is:

const names = ['john', 'james']

Is there a way to get the 2nd letter in 'john' using code?

3 Answers 3

3

You can use the subscript operator ([]) to get a specific element of the array. Then, you can use the subscript operator again to get a specific character from a string:

const result = names[0][1];

Note that both array indexes and string indexes are zero-based.

Sign up to request clarification or add additional context in comments.

Comments

1

function myFunction() {
  var names = ["John", "james", "jacky", "man"];
  var result = names[0][1];
  document.getElementById("demo").innerHTML = result;
}
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

Comments

0

It's also possible to use the substring function.

const names = ['john', 'james'];

//substr(<where to start>, <length of string>)
var letter = names[0].substr(1, 1);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.