Exercise

String interpolation in JavaScript is the process of embedding expressions or variables within a string literal to generate dynamic strings.

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!'

String concatenation in JavaScript involves combining multiple strings using the `+` operator, while string interpolation allows embedding expressions or variables within a template literal string.

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