JavaScript Strings - Exercise 2

String interpolation embeds an expression inside a template literal so its current value becomes part of the resulting text. Use backticks and place the expression between ${...}; JavaScript evaluates it when the template is created.

const name = 'Ada';
const message = `Welcome, ${name}!`;
console.log(message); // Welcome, Ada!

String interpolation in JavaScript can be achieved using template literals, denoted by backticks (\`). Expressions or variables can be embedded within the template literal using the `${}` syntax.

javascript

var name = 'John';
var greeting = `Hello, ${name}!`; // greeting will be 'Hello, John!'

Concatenation joins values with the + operator, so spaces and punctuation must be added explicitly. Interpolation places expressions directly inside a template literal and is often easier to read when a sentence contains several values.

const item = 'book';
const count = 2;
const joined = 'I bought ' + count + ' ' + item + 's.';
const interpolated = `I bought ${count} ${item}s.`;
console.log(joined === interpolated); // true

You can trim whitespace from the beginning and end of a string in JavaScript using the trim() method.

javascript

var str = '   Hello, world!   ';
var trimmedStr = str.trim(); // trimmedStr will be 'Hello, world!'

You can split a string into an array of substrings in JavaScript using the split() method, specifying the delimiter as an argument.

javascript

var str = 'apple,banana,orange';
var fruits = str.split(','); // fruits will be ['apple', 'banana', 'orange']

You can reverse a string in JavaScript using various methods, such as using the split() method, reverse() method, and join() method.

javascript

var str = 'hello';
var reversedStr = str.split('').reverse().join(''); // reversedStr will be 'olleh'

You can replace a substring within a string in JavaScript using the replace() method, specifying the substring to be replaced and the new substring as arguments.

javascript

var str = 'Hello, world!';
var newStr = str.replace('world', 'JavaScript'); // newStr will be 'Hello, JavaScript!'

You can check if a string starts or ends with a specific substring in JavaScript using the startsWith() method and endsWith() method, respectively.

javascript

var str = 'Hello, world!';
var startsWithHello = str.startsWith('Hello'); // startsWithHello will be true
var endsWithWorld = str.endsWith('world!'); // endsWithWorld will be true

You can extract the first or last character of a string in JavaScript using square brackets notation ([]), with index 0 for the first character and negative index -1 for the last character.

javascript

var str = 'JavaScript';
var firstChar = str[0]; // firstChar will be 'J'
var lastChar = str[str.length - 1]; // lastChar will be 't'

You can check if a string is empty in JavaScript by comparing its length to 0.

javascript

var str = '';
var isEmpty = str.length === 0; // isEmpty will be true