CharAt
A Node.js string
may contain many characters. We can iterate over these characters with a for
-loop, and then index the characters or use charAt
.
With the result from charAt
, we can access other arrays and objects. This helps us develop complex algorithms and thus improve performance.
CharAt
exampleThe charAt
function takes a 1-character string
at an index. It is the same as the string
indexer in functionality.
for
-loop to iterate over the indexes in the string. We call charAt
to get each individual letter.var letters = "abc"; // Loop over all string indexes. for (var i = 0; i < letters.length; i++) { // Use charAt to get a 1-char string. var result = letters.charAt(i); // The letter is a string that is 1 char long. console.log("LETTER: " + result); console.log("LETTER LENGTH: " + result.length); }LETTER: a LETTER LENGTH: 1 LETTER: b LETTER LENGTH: 1 LETTER: c LETTER LENGTH: 1
CharCodeAt
This function converts a character at an index into its ASCII (or Unicode) equivalent int
. It does not handle all Unicode values. But it can handle ASCII strings well.
var letters = "abc"; for (var i = 0; i < letters.length; i++) { // Use charCodeAt to get ASCII values from letters. var point = letters.charCodeAt(i); console.log("CHARCODEAT: " + point); }CHARCODEAT: 97 CHARCODEAT: 98 CHARCODEAT: 99
String.fromCharCode
With charCodeAt
we get a character code from a string
. And with String.fromCharCode
we convert a character code back into a string
.
string
.String.fromCharCode
to convert the code back into a string
.var input = "c"; // Get char code and reduce it by one. var letterCode = input.charCodeAt(0); letterCode--; // Convert char code into a string. var result = String.fromCharCode(letterCode); // Display the values. console.log("INPUT: " + input); console.log("CHARCODEAT: " + letterCode); console.log("FROMCHARCODE: " + result); console.log("LENGTH: " + result.length);INPUT: c CHARCODEAT: 98 FROMCHARCODE: b LENGTH: 1
CharCodeAt
, scan string
With charCodeAt
we can test a string
for multiple values in a single pass. This can avoid excessive loops over a string
with indexOf
.
charCodeAt
loop, we can see if a string
needs further processing, and only call replace()
on it if needed.string
copies and make processing input faster.function hasParentheses(value) { for (var i = 0; i < value.length; i++) { var code = value.charCodeAt(i); switch (code) { case 40: // Left parenthesis. case 41: // Right parenthesis. return true; } } return false; } if (hasParentheses("cat(dog)")) { console.log(true); } if (!hasParentheses("bird")) { console.log(true); }true true
With charAt
, we can optimize certain string
-processing algorithms. We can avoid copying strings repeatedly as multiple transformations are applied.