Home  >  Article  >  Web Front-end  >  Two ways to access a single character in a string using JavaScript_javascript tips

Two ways to access a single character in a string using JavaScript_javascript tips

WBOY
WBOYOriginal
2016-05-16 15:51:411660browse

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:

Copy code The code is as follows:



charAt() function accesses a single character
Directly upload the code:
Copy code 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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn