How to work with strings (e.g., concatenation, substring) in JavaScript?

Working with strings in JavaScript is fairly straightforward. Here are some common operations you can perform on strings:

  1. Concatenation: To join two or more strings together, you can use the "+" operator or the concat() method.

    const str1 = "Hello"; const str2 = "World"; const result = str1 + " " + str2; // Using the "+" operator // Or const result = str1.concat(" ", str2); // Using the concat() method
  2. Substring: To extract a substring from a string, you can use the slice() or substring() methods.

    const str = "Hello World"; const substring = str.slice(6, 11); // Extracts "World" // Or const substring = str.substring(6, 11); // Extracts "World"
  3. Length: To get the length of a string, you can use the length property.

    const str = "Hello World"; const length = str.length; // Returns 11
  4. Upper/Lower Case: To convert a string to uppercase or lowercase, you can use the toUpperCase() and toLowerCase() methods, respectively.

    const str = "Hello World"; const uppercaseStr = str.toUpperCase(); // "HELLO WORLD" const lowercaseStr = str.toLowerCase(); // "hello world"
  5. String interpolation: You can use template literals (enclosed in backticks) to insert expressions or variables within strings.

    const name = "Alice"; const age = 25; const greetings = `My name is ${name} and I am ${age} years old.`; // "My name is Alice and I am 25 years old."
  6. Searching: To find the index of a character or a substring within a string, you can use the indexOf() or lastIndexOf() methods.

    const str = "Hello World"; const index = str.indexOf("World"); // Returns 6 // Or const lastIndex = str.lastIndexOf("o"); // Returns 7

These are just a few operations commonly used with strings in JavaScript. There are many more methods available for string manipulation, so you can explore the JavaScript documentation for further details.