2

How can I make my string.charAt() look for multiple characters at once? I'm looking to reduce the lines of code I have in my program, just wondering how I can fit multiple characters into one line.

Example: normally I would type

(string.charAt(4));

if i wanted to find the character at spot 4, what if I wanted to find the character at spots 3-5? would i write

(string.charAt(3-5));

Thanks in advance!

4
  • 2
    Q: Can string.charAt() look for multiple characters at once? A: No. String.charAt() doesn't "look at" ANY "characters". It turns THE character at THE SPECIFIED "index". Q: Could you show us an example string, what describe what you'd like to "look for"? I suspect maybe you can use a regex Commented Aug 9, 2020 at 23:14
  • the java language does not have a charAt method for the string class Commented Aug 9, 2020 at 23:24
  • 1
    Riley, you may want to edit your title to reflect "Javascript" as opposed to "Java". Both exist and differ quite a bit. The charAt() method belongs to Javascript. And I second @paulsm4 request to show us an example. This will help you find your answer. Commented Aug 9, 2020 at 23:41
  • Why not string[i], where i is the index. Commented Aug 9, 2020 at 23:43

1 Answer 1

1

You can use slice() method if you want to get a portion of a string:

let string = 'Hello World'
console.log(string.slice(2, 6)); 

If you need to get only the letters in specific indexes you can do this:

function getLetters(str, ...args){
    let result = '';
    for(let index in str){
        result += str.charAt(args[index]);
    }
    return result
}

let indexes = [2, 5, 6, 8, 9];
console.log(getLetters(string, ...indexes));

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

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.