JavaScript two ways to access a single character in a string

  • 2020-07-21 06:45:43
  • OfStack

An overview of the

JavaScript is a very flexible language and provides many native functions for programming. This article focuses on how to access individual characters in a string in javascript.
javascript 1 is an object, and there are two main ways to access a single character in a string: the array index and the charAt() function.

Index and charAt ()

Index access to a single string
In javascript, strings can be treated as arrays, so we can access individual characters as array subscripts. The code is as follows:


<script type="text/javascript">
    var str="hello world";
    console.log(str[0]); // The output h
</script>

The charAt() function accesses a single character
Direct code:

<script type="text/javascript">
    var str="hello world";
    console.log(str.charAt(1));  // The output e
</script>

The difference between the two approaches

1. The first difference is the difference in the return values that are out of range
Using string[index], undefined is returned for words outside the scope of index.
With charAt(index), an empty string is returned for those out of range.
2. The second difference is compatibility
The string[index] method returns undefined under IE6-8, which means es40EN6-8 is not compatible with this method.
However, charAt(index) can also return normally under IE6~8 after testing.

conclusion

If you don't need to worry about IE6 ~ 8, you can just use it. As for performance, it's all JavaScript methods, with little difference.
If you still have no choice but to consider IE6 ~ 8, it is better to use charAt(), which is safe and assured.


Related articles: