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!

paulsm4
  • 114,292
  • 17
  • 138
  • 190
  • 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](http://tutorials.jenkov.com/java-regex/index.html) – paulsm4 Aug 09 '20 at 23:14
  • the java language does not have a charAt method for the string class – Mister Jojo Aug 09 '20 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. – Josh Cronkhite Aug 09 '20 at 23:41
  • Why not `string[i]`, where `i` is the index. – Felipe Oriani Aug 09 '20 at 23:43

1 Answers1

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));
sonEtLumiere
  • 4,461
  • 3
  • 8
  • 35