Fall 2024 - P2
Big Idea 3 | .1 | .2 | .3 | .4 | .5 | .6 | .7 | .8 | .10 |
3.4 Javascript Strings
Gain and understanding of how strings work
Strings & Palindromes in Javascript
Javascript Strings
The concepts of Python Strings & Javascript Strings are the same, however the way these concepts are implemented across these two languages vary, and there are some important distinctions that’ll be highlighted in this blog. If you haven’t already, check out the first blog
Making Strings
When it comes to making strings, there are three ways of going about it— Each method requiring that you surround the text you want to make a string with these characters. These methods are listed below:
Single Quotes (‘’) Double Quotes (“”) Backticks (``)
Single Quotes and Double Quotes are the most conventionally used and serve the same purpose. Surrounding text as to delineate them as strings and not another data type. So most of the time, you’ll be using either single or double quotes.
However, the last option, strings that use backticks (known as template strings), are also very important to know and a proficient coder in Javascript will take advantage of this type of string when the opportunity arises. We’ll come back to this string later, but what you should know now is that it allows you to implant javascript code that isn’t inherently a string into your string, such as a variable.
To confirm whether a variable is a string or not, you can put the potential string inside typeof().
%%js
let intro = 'Your Journey Begins Here.'
let fruit = "orange"
// Checking if string
typeof(intro) //Output: True
typeof(fruit) //Output: True
<IPython.core.display.Javascript object>
Concatenation
Concatenation is the combining or joining of different strings. It allows us to take one string and merge it with another. Refer to the example below:
%%js
let greeting = "Hello " + "Class";
console.log(greeting); // Output: Hello Class
let word = "Break" + "fast";
console.log(word) //Output: Breakfast
console.log ( greeting + word ) //Output: Hello Class Breakfast
<IPython.core.display.Javascript object>
Concatenation is used to address the need to keep strings separate for storing dynamic data (like user input) and then combine them into a single, cohesive string.
%%js
// Example 1
let favoriteFood = prompt("Enter your favorite food: ");
let favoriteSport = prompt("Enter your favorite sport: ");
let message = "Your favorite food is " + favoriteFood + " and your favorite sport is " + favoriteSport + ".";
console.log(message);
<IPython.core.display.Javascript object>
// Example 2
let dreamVacation = prompt("Enter your dream vacation destination: ");
let favoriteSeason = prompt("Enter your favorite season: ");
let vacationMessage = "Your dream vacation is to " + dreamVacation + " and your favorite season is " + favoriteSeason + ".";
console.log(vacationMessage);
Cell In[4], line 1
// Example 2
^
SyntaxError: invalid syntax
String Interpolation
String interpolation brings us back to using backticks, also known as template strings. Rather than combining multiple strings, template strings allow us to embed variables and JavaScript expressions directly within the string.
The following examples are the same as the ones above, but we utilize interpolation instead of concatenation:
%%js
// Example 1
let userHobby = prompt("Enter your hobby: ");
let favoritePlace = prompt("Enter your favorite place: ");
let message = `Your hobby is ${userHobby} and your favorite place is ${favoritePlace}.`;
console.log(message);
As you can see for yourself, interpolation is much cleaner & efficient than concatenation. The only things you need to do in order to interpolate a string is to:
Use backticks
Surround the variable or javascript expression in ${variable_here}
Indexing a Character
Indexing a character is just a more technically correct way of saying how to access a character within a string. Each character in a string is assigned a number that we can use to access it individually.
%%js
let fruit = "Banana";
console.log(fruit[1]); // Output: a
console.log(fruit.at(1)); // Output: a
console.log(fruit[6]); // Output: undefined
console.log(fruit.at(6)); // Output: undefined
In the Python Strings lesson, we learned that indexing starts at 0, and negative numbers can be used to count backwards. In JavaScript, you can access characters in two ways:
Using brackets: [#] Using the at method: .at(#) I recommend using the at() method, as brackets cannot handle negative indices (resulting in undefined) unless you implement additional steps, which makes it unnecessarily complicated.
Substrings
There are 3 ways to retrieve a substring in JavaScript: substring, substr, & slice
For this blog post, we’ll be exclusively covering slice which is arguably the most flexible of the three options. Feel free to look into the others, but keep in mind slice can do anything the other methods can and more.
Substrings is a part of a string that we have taken using the slice function. It allows us to take more than one character as indexing allows.
The slice() method extracts characters from a string between two specified indices and returns a new string. It takes two parameters:
The starting index (inclusive) The ending index (exclusive)
%%js
let greeting = "Goodbye, Universe!";
let city = "San Francisco";
let continent = "North America";
// Extract and display "Goodbye" from the greeting
console.log(greeting.slice(0, 7)); // Output: Goodbye
// Extract and display "Universe" from the greeting
console.log(greeting.slice(-8)); // Output: Universe
// Display everything from the second character onward in city
console.log(city.slice(1)); // Output: an Francisco
// Display everything from the third character onward in city
console.log(city.slice(-9)); // Output: Francisco
// Extract substring starting from index 4 and ending before the last index in city
console.log(city.slice(4, -3)); // Output: Fran
Escape Characters
The \ is often known as the escape character as inputting it into a string allows you to temporarily escape the string and add something to the string that isn’t just text (or text that can’t be added conventionally).
Here are some of the most common uses:
%%js
let message = "Goodbye Universe";
// Create a new line
console.log("Goodbye\nUniverse"); // Output: Goodbye
// Universe
// Create a horizontal tab
console.log("Goodbye\tUniverse"); // Output: Goodbye Universe
// Create a backslash
console.log("Goodbye\\Universe"); // Output: Goodbye\Universe
// Add a unicode character
console.log("\u2731"); // Output: ✱ (a star character)