A shortcut to get the last char of string? This maybe not useable in JavaScript

Revision en1, by zhanglinjie_, 2022-02-21 09:38:42

In both python and JavaScript we can access the char of string with bracket:

in python

s = "abc"
s[0]
# it returns 'a'

in JavaScript

s = "abc"
s[0]
// it returns 'a'

But if we use the index -1 to get the last char

in python

s[-1]
# it returns 'c'

in JavaScript

s[-1]
# it returns undefined

Fortunately, we can simply use s[s.length - 1].

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English zhanglinjie_ 2022-02-21 09:38:42 494 Initial revision (published)