Grab Character(s) At Certain Position In String With JavaScript
July 17, 2020 by Andreas Wik
To grab one or more characters at a certain position in a string, the built-in JavaScript function substr() is really handy.
It takes two arguments, the position where to start (as with arrays, the index starts with 0, so the third character in a string would be at position 2) and how many characters to extract.
Let’s say we got the following string:
const movie = 'Bad Taste'
To grab the first character in the string we would tell substr() to start at 0 and grab 1 character.
// Get first character
const firstChar = movie.substr(0, 1)
console.log(`First character is ${firstChar}`)
Same thing but grabbing the third character in the string.
// Get third character
const thirdChar = movie.substr(2, 1)
console.log(`Third character is ${thirdChar}`)
To extract the last character of the string we can use the string’s length minus one to get the position of the it.
// Get last character
const lastChar = movie.substr(movie.length-1, 1)
console.log(`Last character is ${lastChar}`)
To grab multiple characters, change the second argument to your desired number.
// Get first 3 characters
const firstThreeChars = movie.substr(0, 3)
console.log(`First 3 characters are ${firstThreeChars}`)
JSFiddle: