JavaScript Strings
JavaScript Strings are immutable sequences of ordered characters, which are
stored in 16 bits. If a character can’t fit in 16 bits, JavaScript use the
UTF-16
encoding. As the length of the string is determinate by the number of 10-bits that
compose it, if a character needs 32 bits, its length
will be reported as 2.
let euro = "€"; let smile = "😄"; console.log(euro.length); // => 1: this character has one 16-bit element console.log(smile.length); // => 2
When JavaScript iterates over a string, this issue disappears
let text = "This string has a 😄 smile"; for (let i = 0; i < text.length; ++i) process.stdout.write(text[i]); process.stdout.write("\n"); for (let c of text) process.stdout.write(c); process.stdout.write("\n");
Strings literals
To include a string in JavaScript, you can enclose the characters in either single quotes, double quotes, or back-ticks.
let s1 = "This is a string"; let s2 = 'This is another string'; let s3 = `This is also a valid string`;
Operations with Strings
To create a string from different variables, we can use the +
operator
let user = "Pepe" let static_string = "Hello " + "World"; let dynamic_string = "Hello, " + user console.log(static_string); console.log(dynamic_string);
Alternative, you can use string templates with back-ticks for a more readable approach. The string templates allows to insert break lines into the text
let user = "Pepe"; let age = 22; let msg = `Hy! I'm ${user} and I'm ${age}`; console.log(msg);
let text1 = "This text has 2 lines\nThis is the second line"; let text2 = `This text has 2 lines This is the second line`; console.log(text2); return text1 === text2;
Strings templates
let n1 = parseInt(Math.random()*10), n2 = parseInt(Math.random()*10); console.log(`${n1} + ${n2} = ${n1 + n2}`);
Strings’ methods
Here are some common string methods in JavaScript:
let myString = "This is a string"; console.log(myString.length); console.log(myString.indexOf("is")); console.log(myString.substring(5)); console.log(myString.substring(5, 8)); console.log(myString.at(-1)); // allows negative index console.log(myString.charAt(0)); // does not allow negative index console.log(myString.charCodeAt(myString.indexOf("a"))); console.log(myString.toUpperCase()); console.log(myString.toLowerCase()); console.log(myString.startsWith("This")); console.log(myString.endsWith("This")); console.log(myString.includes("tri")); console.log(myString.search(/\w{5}/)); console.log(myString.replace("is", "ese").replace("is", "are")); console.log(myString.replaceAll("is", "all")); console.log(myString.slice(5)); console.log(myString.slice(5, 8)); console.log(myString.slice(-5)); console.log(myString.split(" ")); myString = " ".repeat(4) + myString + " ".repeat(4); console.log(`'${myString.trim()}'`); console.log(`'${myString.trimStart()}'`); console.log(`'${myString.trimEnd()}'`);
References:
- JavaScript: The definitive guide : Master the world’s most-used programming language
- MDN Strings