Exercise
A string in JavaScript is a sequence of characters enclosed within single quotes ('') or double quotes (""). It can include letters, digits, symbols, and whitespace.
You can declare a string variable in
JavaScript using the var, let,
or const keyword followed by the variable
name and the string value enclosed in quotes.
var greeting = 'Hello';
let message = "Welcome to JavaScript";
const name = "John Doe";
You can find the length of a string in
JavaScript using the length property of the
string object. This property returns the number of
characters in the string.
var message = 'Hello, world!';
var length = message.length; // length will be 13
You can access individual characters in a string in JavaScript using square brackets notation ([]), with the index of the character you want to access. JavaScript strings are zero-indexed, meaning the first character has an index of 0.
var str = 'JavaScript';
var firstChar = str[0]; // firstChar will be 'J'
var thirdChar = str[2]; // thirdChar will be 'v'
You can concatenate strings in
JavaScript using the + operator or the
concat() method.
var firstName = 'John';
var lastName = 'Doe';
var fullName = firstName + ' ' + lastName; // fullName will be 'John Doe'
var fullNameConcat = firstName.concat(' ', lastName); // fullNameConcat will be 'John Doe'
In JavaScript, a string primitive is a string value that is not an object, while a string object is a wrapper around a string primitive that provides additional string-related methods and properties.
You can convert a string to
uppercase in JavaScript using the
toUpperCase() method.
var str = 'hello';
var uppercaseStr = str.toUpperCase(); // uppercaseStr will be 'HELLO'
You can convert a string to
lowercase in JavaScript using the
toLowerCase() method.
var str = 'HELLO';
var lowercaseStr = str.toLowerCase(); // lowercaseStr will be 'hello'
You can check if a string contains a specific
substring in JavaScript using the
includes() method or the
indexOf() method.
var str = 'JavaScript is awesome';
var hasSubstring = str.includes('awesome'); // hasSubstring will be true
var index = str.indexOf('awesome'); // index will be 11
You can extract a part of a string in
JavaScript using the substring() method or
the slice() method.
var str = 'JavaScript';
var part1 = str.substring(0, 4); // part1 will be 'Java'
var part2 = str.slice(-6); // part2 will be 'Script'