Javascript built-in data structure - String

This tutorial is a part of the Learn everything about Javascript in one course.

Declaring a string variable

String is usually known as text in real life. Like number, string is one of the most popular used data structures as you can imagine. A lot of information is represented in term of string. Just like the current line of string you are reading. Declaring string variable is fairly simple.

string.js
// ways to declare string variables in Javascript
let str1 = 'hello world' // put text between single quote
let str2 = "hello world in double quotes" // double quotes ok
let str3 = `hello world in backticks` // backticks ok

String template

Only backticks have nice templating feature that we can create a string template and replace part of the string with different strings. For example, a same greeting can be used for different people by changing only their names.

We use ${variable} syntax to escape a variable to the string. Escaping means return the value of that variable.

string.js
// string templating
let name1 = 'John' // put text between single quote
let name2 = "Linda" // double quotes ok

const greet = (name) => console.log(`Hello, ${name}`) // print out greeting

greet(name1) // Hello, John
greet(name2) // Hello, Linda

String variable automatically inherits useful methods of blobal String object. We will have a look at frequently used ones.

String length

Is the number of characters in a string. This is a string property, we access it by calling variableName.length.

string.js
// string length
let myStr = 'hello John!'
console.log('myStr length is:', myStr.length) // myStr length is: 11

Get to a character in string with index

String automatically has a number assigned to each character, starting from 0. We can get a character with a specified index by two ways:

  1. syntax variableName[indexNumber]
  2. use charAt method
string.js
// Get a character with index
// in this example, the string is 'hello John!'
// variableName -> myStr
// indexNumber -> 6
console.log('character at index 6 is:', myStr[6]) // character at index 6 is: J
console.log('character at index 6 is:', myStr.charAt(6)) // same output: character at index 6 is: J

UTF-16 table to lookup character code

Is a table to lookup a number (a code) associated with a character. Why this table? Because computer don't understand character. And characters are actually turned into numbers before transfered in the internet. A part of the UTF-16 table is as follow:

Character Decimal code
... ...
a 97
b 98
c 99
d 100
e 101
f 102
g 103
h 104
i 105
j 106
k 107
l 108
m 109
n 110
o 111
p 112
r 113
q 114
s 115
t 116
u 117
v 118
w 119
x 120
y 121
z 122
... ...

The full table of all characters and codes can be found here

Looking up the code is usually useful. So Javascript String data structure has a built in function to do it called charCodeAt.

Get UTF-16 code at an index

string.js
// by using built-in 'charCodeAt' method
const indexNum = 0
console.log(`character at index '${indexNum}' is: '${myStr.charAt(0)}', UTF16 code number is: ${myStr.charCodeAt(0)}`)
// character at index '0' is: 'h', UTF16 code number is: 104

Split string into array of shorter strings

split method takes optional input string separator and return the array of shorter strings. split method does not modify the original string

string.js
// split string to array of shorter strings
// in this example
// 'string separator' is character comma ','
const longStr = 'hello world, from SESV!'
console.log(longStr.split(',')) // [ 'hello world', ' from SESV!' ]
// 'string separator' is empty space character ' '
console.log(longStr.split(' ')) // [ 'hello', 'world,', 'from', 'SESV!' ]
console.log(longStr) // hello world, from SESV!, original string is not modified

Get a substring with 2 indices

substring method takes 2 inputs as start and end index and return all characters between these 2 indices. Always remember, in Javascript it's 0-indexed meaning index always starts with 0. substring method does not modify original string.

slice method can do the same with same syntax.

string.js
// Get a substring with 2 indices
// in this example, we will get 'world' in 'hello world, from SESV!'
// start index = 6 (included)
// end index = 11 (excluded)
console.log(longStr.substring(6, 11)) // world, include 6, exclude 11
console.log(longStr.slice(6, 11)) // world

Lower case all character in string

toLowerCase method return a string with all cases lowered. The original string is not modified.

string.js
// Lower case all character in string
let sentence = `It's always sunny in Sunnyvale.`
console.log(sentence.toLowerCase()) // 'it's always sunny in sunnyvale.'
console.log(sentence) // 'It's always sunny in Sunnyvale.', un-modified

Upper case all character in string

toUpperCase method return a string with all cases upperred. The original string is not modified.

string.js
// Upper case all character in string
console.log(sentence.toUpperCase()) // 'IT'S ALWAYS SUNNY IN SUNNYVALE.'
console.log(sentence) // 'It's always sunny in Sunnyvale.', un-modified

Full list of properties and methods of String data structure can be found in MDN.

Summary

  1. String data structure in Javascript helps to represent real life text.
  2. What you can do with real life text, you can do the same with Javascript.