C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
For: We use the for-loop to iterate over the indexes in the string. We call charAt to get each individual letter.
forStringsJavaScript program that uses charAt
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);
}
Output
LETTER: a
LETTER LENGTH: 1
LETTER: b
LETTER LENGTH: 1
LETTER: c
LETTER LENGTH: 1
JavaScript program that uses charCodeAt
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);
}
Output
CHARCODEAT: 97
CHARCODEAT: 98
CHARCODEAT: 99
Tip: With a character code, we can change the character value by adding or subtracting (like a number). We cannot do this with a string.
Tip 2: After the transformation, we can call String.fromCharCode to convert the code back into a string.
JavaScript program that uses String.fromCharCode
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);
Output
INPUT: c
CHARCODEAT: 98
FROMCHARCODE: b
LENGTH: 1
Tip: With a charCodeAt loop, we can see if a string needs further processing, and only call replace() on it if needed.
Tip 2: This style of code can yield significant performance benefits—it can reduce string copies and make processing input faster.
JavaScript program that uses charCodeAt to scan string
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);
}
Output
true
true