JavaScript Strings - Exercise 1
A string in JavaScript is a sequence of characters enclosed within quotes. Backticks also create strings and support interpolation or multiline text, while all string values are immutable. The example stores letters, a space, and punctuation as one string.
const greeting = 'Hello, JavaScript!';
console.log(greeting.length); // 18
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'
A string primitive is the normal text value and is usually preferred because it is simple and efficient. A String object wraps text in an object, so its type is different; JavaScript temporarily boxes primitives when you call methods such as toUpperCase().
const primitive = 'hello';
const objectString = new String('hello');
console.log(typeof primitive); // "string"
console.log(typeof objectString); // "object"
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'