Week 3 - Functions and strings

Functions

String functions

JavaScript Modules

Scope

IDE navigation

DRY (Don’t Repeat Yourself)

Function size

Using LLMs for efficient learning

Practice

Assignment

Back to core program

String functions

Last week you already learned about data types and a little bit about what a String is, but a String can do so much more than that. A String is actually a type of Object. Currently you don’t need to know what this means, we’ll dive deeper into that next week, however what you should know now is that there are some standard functions implemented on a String. We’ll talk about some of the most useful ones in this section.

Concatenation

Concatenation is just a fancy word for putting multiple strings after each other. We can do this by calling the concat function on the first string with the second string. You can even provide multiple arguments to the concat function and it will put them all together. Let’s look at some examples:

// Example 1: Using concat() with one argument
const greeting = "Hello";
const name = "World";
const message = greeting.concat(name);
console.log(message); // Output: "HelloWorld"

// Example 2: Using concat() with multiple arguments
const firstName = "John";
const greeting2 = firstName.concat(" ", "Doe", ", ", "welcome!");
console.log(greeting2); // Output: "John Doe, welcome!"

As this is so common, there is also a shorthand version that you can use, the + notation. Let’s rewrite the first example using this notation:

const greeting = "Hello";
const name = "World";
const message = greeting + name;
console.log(message); // Output: HelloWorld 

<aside> ⌨️

Hands on: Rewrite the second example to use the + notation

</aside>

Template Strings

Even the + notation could be improved, so in modern JavaScript the concept of template strings were introduced. A template string uses the ` character (a backtick) to define a new string. It is easiest to show you how to use it by rewriting the above example:

// Example: Using template strings (backticks)
const name = "World";
const message = `Hello ${name}`;
console.log(message); // Output: "Hello World"

<aside>

⚠️ Template strings use the backtick character ` (not a regular quote ‘). You should see that you are using the correct one when the syntax highlighting shows the variable name as a different colour.

</aside>

Let’s look at the syntax. We use the character to surround the template string. Inside that template string we can type text like we can with regular strings. The cool thing is when we want to put a variable inside the string, then we can use the${}` syntax to tell JavaScript where to add it.

<aside> ⌨️

Hands on: Rewrite the second example using the template string notation

</aside>

Most of the time you will want use template strings when you are working with concatenating strings so try to make it your standard.

Trim

trim() is another function that we use a lot. We cannot control what users enter into the data fields and you would be surprised how often there is a leading or trailing space in there. When we then later try to compare this value with the extra space with a value without one the computer will say they are different, but us humans see them as the same. So a common practice is to trim any text input from the user. Let’s look at some code:

// Example: Problems with spaces around input
const userInput = "Hello World ";  // User accidentally added space at the end
const expectedText = "Hello World";

// Without trim - comparison fails
console.log(userInput === expectedText);  // Output: false

// With trim - comparison succeeds
const trimmedInput = userInput.trim();
console.log(trimmedInput === expectedText);  // Output: true

<aside> 💡

Note that trim() does not remove spaces in the middle of the string, it only removes leading and trailing spaces!

</aside>

Uppercase/Lowercase

Another common thing that we need to is convert a string to uppercase or lowercase letters. JavaScript provides already defined functions for us here too, toUpperCase() and toLowerCase(). These are quite straight forward:

// Example 1: Converting to uppercase
const lowerCaseText = "hello world";
const upperCaseText = lowerCaseText.toUpperCase();
console.log(upperCaseText); // Output: "HELLO WORLD"

// Example 2: Converting to lowercase
const mixedCaseText = "JavaScript Is AWESOME";
const lowerCaseVersion = mixedCaseText.toLowerCase();
console.log(lowerCaseVersion); // Output: "javascript is awesome"

You may think why we do this so much, well the reason is similar to the trim function. When comparing two strings, the computer sees a capital ‘A’ and a lowercase ‘a’ as two different things, which is technically true. However, most of the time when we are searching for something in the data, we don’t want to be this strict. In this example you can see that a user typing ‘Javascript’ is probably also looking for the official way of writing ‘JavaScript’.

const userInput = "Javascript";
const expectedValue = "JavaScript";

// Without conversion - comparison fails
console.log(userInput === expectedValue); // Output: false

// With conversion - comparison succeeds
console.log(userInput.toLowerCase() === expectedValue.toLowerCase()); // Output: true

<aside> 💡

We call this ‘case-insensitive’

</aside>

Replace

Sometimes we want to manipulate strings, a common way of doing that is using the replace() function. It has 2 parameters, the first the substring it needs to match to and the second what it should replace it with. This works very much the same as the find and replace functionality in your IDE. For example:

// Example: Using replace() to change part of a string
const originalText = "I love cats";
const newText = originalText.replace("cats", "dogs");
console.log(newText); // Output: "I love dogs"

// Example 2: Replace only replaces the first occurrence
const sentence = "The cat sat on the cat";
const updatedSentence = sentence.replace("cat", "dog");
console.log(updatedSentence); // Output: "The dog sat on the cat"

<aside>

💡The replace() function only replaces the first occurrence of the substring. To replace all occurrences, you can use replaceAll() instead.

</aside>

Substring

Until now we have only worked with the whole String, but sometimes we want to extract a part of a String to work with. In this case we can use the substring() function. The first parameter is the index of the character we want to start the extraction from, the second the index of the character we want to end. If we want the rest of the string we can also just give one argument.

<aside> 💡

Remember that indexes in JavaScript start from 0, so 0 is the first character, 1 is the second, etc.

</aside>

// Example: Extracting day, month, and year from a date string
const dateString = "2025-11-23"; // Format: YYYY-MM-DD

// Extract year (characters 0-4)
const year = dateString.substring(0, 4);
console.log(year); // Output: "2025"

// Extract month (characters 5-7)
const month = dateString.substring(5, 7);
console.log(month); // Output: "11"

// Extract day (characters 8-10)
const day = dateString.substring(8, 10);
console.log(day); // Output: "23"

// Or extract everything from a certain position to the end
const monthAndDay = dateString.substring(5);
console.log(monthAndDay); // Output: "11-23"

<aside>

⌨️ Hands on: Try extracting the day, month, and year from a date string in DD/MM/YYYY format like "23/11/2025"

</aside>

StartsWith/EndsWith/Includes

Often times we want to do some logic based on the value of a string. We have a few options here that are named very well as they describe what they do: startsWith() , endsWith() and includes(). Again, it is easiest to just show you:

// Real-world example: Processing user input for file upload validation
const fileName = "report_2025.pdf";
const userEmail = "[email protected]";

// Example 1: Check if file has allowed extension using endsWith()
const isPDF = fileName.endsWith(".pdf");
console.log(`${fileName} is a PDF file: ${isPDF}`); // Output: report_2025.pdf is PDF file: true

// Example 2: Check if filename has proper prefix using startsWith()
const hasReportPrefix = fileName.startsWith("report_");
console.log(`${fileName} has the report prefix: ${hasReportPrefix}`); 
// Output: report_2025.pdf has the report prefix: true

// Example 3: Search for specific content using includes()
const searchQuery = "2025";
const containsYear = fileName.includes(searchQuery);
console.log(`${fileName} contains the year 2025: ${containsYear}`); 
// Output: report_2025.pdf contains the year 2025: true

Summary of the commands

Function Description Notes
concat() Returns a new string with all of the arguments placed after each other There is a shorthand way:
string1 + string2
trim() Returns a new string without any leading or trailing spaces If you only want to trim trailing spaces you can use trimEnd() . If you only want to trim leading spaces you can use trimStart()
toUpperCase() Returns a new string with all the letters converted to upper case
toLowerCase() Returns a new string with all the letters converted to lower case
replace(toReplace, replaceWith) Returns a new string where the first occurrence of the first argument is replaced with the second argument If you want to replace every occurrence then use replaceAll()
substring(startIndex, endIndex) Returns a new string that starts from the startIndex argument until the endIndex argument If you only want to ignore the first part of a string you can also call it with just one argument
startsWith(toCheck) Returns a boolean that returns true if the string starts with the exact string given in the toCheck argument. Otherwise it returns false
endsWith(toCheck) Returns a boolean that returns true if the string ends with the exact string given in the toCheck argument. Otherwise it returns false
includes(toCheck) Returns a boolean that returns true if the string contains the exact string given in the toCheck argument. Otherwise it returns false

Extra reading


The HackYourFuture curriculum is licensed under CC BY-NC-SA 4.0 **

CC BY-NC-SA 4.0 Icons

*https://hackyourfuture.net/*