Working with strings

The following topics are covered:

  • Access characters from a string using bracket notation.
  • Create newlines and escaping strings
  • Find the position of a substring in a string
  • The prompt() method

Bracket notation

Use the index of a character within a string to access it’s value. The first character of a string is [0] – known as being ‘zero-based’.

let greeting = "hello";
console.log(greeting[1]); // "e"

Getting the last character of a string

To get the last character of a string, you can use the length of the string -1 as the index:

let greeting = "hello";
console.log(greeting[greeting.length -1]); // "0"

In this case, the length of the string is 5 - 1 = index 4.

Concatenation with bracket notation

let greeting = "hello";
let firstTwo = greeting[0] + greeting[1];
console.log(firstTwo); // "he"

Newline

Use the /n escape sequence to create a newline in JavaScript.

let poem = "Roses are red,\nViolets are blue, \nJavaScript is fun,\nAnd so are you.";
console.log(poem); 

/*
"Roses are red,
Violets are blue, 
JavaScript is fun, 
And so are you."
*/

Escape special JavaScript characters

Use the \ backslash to indicate the the character following it is literal and is not to be interpreted as being part of JavaScript code or syntax.

let statement = "She said, \"Hello\"";
console.log(statement); // "She said, "Hello!""

This prevents errors.

Template literals and string interpolation

Template literals use backticks and are an easier way than concatenation to create strings that

  • embed variables directly in the sting (string interpolation)
  • span multiple lines
  • include code

String interpolation is inserting variables and expressions directly into a string.

Example of a template literal, with backticks and ${}:

const name = "Alice";
const greeting = `Hello, ${name}!`:

console.log(greeting); // "Hello, Alice!"

Multiple lines, as template literal preserve line breaks:

let poem = `Roses are red,
Violets are blue, 
JavaScript is fun, 
And so are you!`; 

console.log(poem);

Embed JavaScript expressions:

const score = 9.5;
const highScore = 10;
const output = `I rate it ${
    (score/highScore) * 100
}%.`;

console.log(output); // "I rate it 95%.

Declaring template literals

We can use const to declare template literals. The value might be variable, but the name of the variable doesn’t change (I guess) making let not really needed.

The indexOf() method

Find the position of a substring

A substring is a sequence of characters within a larger string. For example, ‘hello’ and ‘world’ are substrings of ‘hello world’.

Use the `indexOf() method to search for a substring within a string.

  • returns -1 if no match was found
  • returns the index of the substring’s first character, e.g. 14

The first argument is the substring and it’s case sensitive.

let sentence = "JavaScript is awesome!";
let position = sentence.indexOf("awesome!");
console.log(position); // 14

The second, optional, argument it the starting position of the search

let sentence = "JavaScript is awesome, and JavaScript is powerful!";
let position = sentence.indexOf("JavaScript", 10); 

console.log(position); // 27

The prompt() method

A simple way to get input from a user by presenting a small dialog window with an input box.

After the user enters something, the prompt method returns the entered text.

prompt(message, default);

  1. The first argument is the message that will appear in the dialog box.
  2. The (optional) second argument is default text to initially be in the input box (placeholder text?).
const btn = document.getElementById("prompt-btn");
const output = document.getElementById("output");
btn.addEventListener("click", () => {
  const userName = prompt("What is your name?", "Guest");
  output.textContent = "Hello, " + userName + "!";
});

The userName variable stores the entered value if the user types and submits something. Otherwise the value will be null. The output paragraph will display “Hello, Guest” if the value is null, otherwise it will display the name of whatever the person entered.

The prompt() method is useful for testing or small applications but not used in modern web development.

ASCII, charCodeAt(), and fromCharCode()

American Standard Code Information Exchange (ASCII) encodes characters into numerical vales and is universally recognized by machines, allowing computers to store and manipulate text.

For example, A is represented as 65 and aas97`. There are 128 characters in standard ASCII, including:

  • Upper and lowercase English letters
  • Numbers 0 to 9
  • Common punctuation (!. @, # and so on)
  • Control characters (newline and tab)

The ASCII methods in JavaScript are way to compare characters based on ASCII values. You could verify if a character is upper or lowercase with charCodeAt() and dynamically generate characters from their ASCII codes with fromCharCode().

Use charCodeAt() to find the ASCII code

This method on a string returns the ASCII code of the character at a specified index.

For example, return the ASCII value of the first character 0 in the string “A”.

let letter = "A";
console.log(letter.charCodeAt(0)); // 65

Use fromCharCode to find the character

For example, convert the ASCII value 65 back to the letter A. I’m not sure what this String object is about though.

(fromcharCode is a static method that doesn’t need an instantiation string to work. Claude says, “The distinction is: static methods are general utilities that don’t need an existing string to work on, while instance methods operate on a specific string value.”)

let char = String.fromCharCode(65);
console.log(char); // A

String search and slice methods

The includes() method

Test if a string contains a substring with includes(). It returns a boolean value of true or false and takes two arguments:

  1. The substring to search for (case sensitive)
  2. Optional. The index of where to begin searching.
let phrase = "JavaScript is awesome";
let result = phrase.includes('awesome', 7);

console.log(result); // true

Useful for checking if a user’s input contains a specific character or word before performing some action.

But if you want to know the location of the substring, use the indexOf() method instead.

The slice() method

Create a new string with a portion of the original string.

The endIndex parameter is optional and excludes the character at that index. If not provided, the slice will be cut to the end of the original string by default. Negative indexes count from the end of the string.

string.slice(startIndex, endIndex);

For example:

let message = "Hello, world!";

let greeting = message.slice(0, 5);
console.log(greeting); // Hello

let world = message.slice(-6);
console.log(world); // world!

String formatting methods

Change the casing of a string and remove whitespace. These methods don’t take any arguments but are called on a String object.

The toUpperCase() and toLowerCase() methods

Transform letters to uppercase for a heading or lowercase for consistency. The methods return a new string and the original one remains.

Change all letters to lowercase with toLowerCase():

let shout = "I AM LEARNING JAVASCRIPT";
let lowercaseShout = shout.toLowerCase();
console.log(lowercaseShout); // "i am learning javascript!"

Change all letters to uppercase with toUpperCase():

let greeting = "Hello, World!";
let uppercaseGreeting = greeting.toUpperCase();
console.log(uppercaseGreeting); // "HELLO, WORLD!"

The trim(), trimStart(), and trimEnd() methods

Whitespace can interfere with comparisons, storage, display. Whitespace refers to spaces, tabs, or line breaks that occur in a string that are not visible characters.

  • The trim() method removes whitespace from the beginning and end of a string, and leaves whitespace between words in.
let message = " Hello there!  ";
let trimmedMessage = message.trim();
console.log(trimmedMessage); // "Hello there!"
  • Remove whitespace from only the start or the end of a string.
let greeting = "  Hello! ";

let trimmedStart = greeting.trimStart();
console.log(trimmedStart); // "Hello! "

let trimmedEnd = greeting.trimEnd();
console.log(trimmedEnd); // " Hello!"

String modification methods

Replace a portion of a string (it creates a new string) an repeat a string x number of times.

The replace() method

The replace() method is useful for updating user info in a URL, change date formatting, and correct errors.

The syntax:

string.replace(searchValue, newValue);

The arguments are case sensitive and if there is no match the same, unchanged string is returned.

  • Search for the value in the string to replace using the first argument (can be a string or regex). Only the first match is replaced.
  • the newValue argument is what you want to replace the located substring with.
let phrase = "Hello, world! Welcome to the world of coding.";
let updatedPhrase = phrase.replace("world", "universe");

console.log(updatedPhrase); // "Hello, universe! Welcome to the world of coding."

The replaceAll() method

The replaceAll() method replaces all instances of the searchValue with the newValue argument.

The syntax:

string.replace(searchValue, newValue);

The repeat() method

The repeat() method is useful for repeating patterns and duplicating text and can save you from writing loops of more complex code.

string.repeat(count);

The string can be an object or literal like "hello.repeat(2)" The count argument specifies how many times you want the string to be repeated, but with limitations:

  • The number must be positive (or throws a RangeError)
  • It can’t be Infinity (or throws a RangeError)
  • Decimals are round down to the nearest integer
  • 0 will return an empty string (like "")

Example:

let word = "Hello";
let repeatedWord = word.repeat(3);

console.log(repeatedWord); // "Hello!Hello!Hello!"

Strings review

https://www.freecodecamp.org/learn/javascript-v9/review-javascript-strings/review-javascript-strings