Overview
JavaScript is a very flexible language and provides many native functions for us to use in programming. This article mainly introduces how to access a single character in a string in JavaScript.
Everything in JavaScript is an object. There are two main ways to access a single character in a string: array index and charAt() function.
Indexing and charAt()
Accessing a single string in index mode
In JavaScript, strings can be treated as arrays, so we can access individual characters using array subscripts. The code is as follows:
The difference between the two methods
1. The first difference is that the return value out of range is different
Using the string[index] method, undefined will be returned if it exceeds the range of the word index.
When using charAt(index), an empty string will be returned if the value exceeds the range.
2. The second difference is the compatibility issue
The string[index] method will return undefined under IE6~8, which means IE6~8 is not compatible with this method.
After testing, charAt(index) can also return values normally under IE6~8.
Summary
If you don’t need to consider IE6~8, you can use it casually. As for performance, they are all JavaScript methods, and the difference is minimal.
If you are still desperate and want to consider IE6~8, it is better to use charAt(), which is safe and secure.