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.
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.
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.
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.
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.
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.
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.
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.
var str = '';
var isEmpty = str.length === 0; // isEmpty will be true