How to access characters of concatenated string in Javascript

Viewed 55

I want to write a function that accesses every n-th element of this concatenated string:


var grid = ( 
  "1 \n" +
  "a 2 F C A E A E ! \n" +
  "G H 3 E L A T \n" +
  "L M N E P U F \n" +
  "X Z R P L")


For instance, the number 1 in the first string, the number 2 in the second string etc. Right now, I already don't know how I can access e.g. the second string. I tried

console.log(grid[3]) 

and

console.log(grid[3][0])

but basically have no idea, how to access the elements of the second, third strings etc. Thanks for reading!

2 Answers

You can do something like that

let grid = 
  "1 \n" +
  "a 2 F C A E A E ! \n" +
  "G H 3 E L A T \n" +
  "L M N E P U F \n" +
  "X Z R P L"
 
function getByCoordinates(a, x, y){
 return a.split('\n').map(x => x.split(' '))[y][x]
}

console.log(getByCoordinates(grid,0,3))

As mentioned in the comments above this is just a string, so there is no build-in method but you can play around with it in anyway you like.

I would suggest you to opperate it as an array. Notice that in order to access one of the digit elements, you must use the value of that digit minus 1, because arrays in javascript are 0 index based.

  const grid =
      "1 \n" +
      "a 2 F C A E A E ! \n" +
      "G H 3 E L A T \n" +
      "L M N E P U F \n" +
      "X Z R P L";

  const asArray = grid
    .split("\n") // Creates an array of lines.
    .map((row) => row.split(" ")); // Creates an array of "characters" from each line, effectively producing a two dimensinal array.

  console.log(asArray[2][2]); // Prints "3".

Related