Table of contents

  • String properties and methods
  • Template literals
  • Example: Manipulating and formatting strings
1. Introduction to Strings

A string in JavaScript is a sequence of characters used to represent text. Strings are immutable, meaning once created, they cannot be changed.

2. Creating Strings

Strings can be created using single quotes ('), double quotes ("), or backticks (`).

Example:
let singleQuoteStr = 'Hello, World!';
let doubleQuoteStr = "Hello, World!";
let templateStr = `Hello, World!`;
Output:
  • singleQuoteStr: “Hello, World!”
  • doubleQuoteStr: “Hello, World!”
  • templateStr: “Hello, World!”
3. String Length

You can find the length of a string using the .length property.

Example:
let myString = "Hello, World!";
console.log(myString.length); // Output: 13
5. Accessing Characters

Strings are indexed, and you can access characters using square brackets or the .charAt() method.

Example:
let myString = "Hello";
console.log(myString[0]); // Output: H
console.log(myString.charAt(1)); // Output: e
5. String Methods

JavaScript provides numerous built-in string methods. Here are some important ones:

  • toUpperCase() and toLowerCase()

Convert strings to uppercase or lowercase.

Example:
let myString = "Hello";
console.log(myString.toUpperCase()); // Output: HELLO
console.log(myString.toLowerCase()); // Output: hello
  • trim()

Remove whitespace from both ends of a string.

Example:
let myString = "   Hello, World!   ";
console.log(myString.trim()); // Output: "Hello, World!"
  • includes()

Check if a string contains a specified substring.

let myString = "Hello, World!";
console.log(myString.includes("World")); // Output: true
console.log(myString.includes("world")); // Output: false
  • indexOf() and lastIndexOf()

Find the position of a substring.

Example:
let myString = "Hello, World!";
console.log(myString.indexOf("o")); // Output: 4
console.log(myString.lastIndexOf("o")); // Output: 8
  • slice() and substring().

Extract parts of a string.

Example:
let myString = "Hello, World!";
console.log(myString.slice(0, 5)); // Output: Hello
console.log(myString.substring(7, 12)); // Output: World
  • split()

Split a string into an array of substrings.

Example:
let myString = "Hello, World!";
let words = myString.split(", ");
console.log(words); // Output: ["Hello", "World!"]
  • replace()

Replace a substring with another substring.

Example:
let myString = "Hello, World!";
let newString = myString.replace("World", "JavaScript");
console.log(newString); // Output: Hello, JavaScript!
6. Template Literals

Template literals allow for multi-line strings and string interpolation using backticks.

Example:
let name = "John";
let greeting = `Hello, ${name}!`;
console.log(greeting); // Output: Hello, John!

let multiLine = `This is a string
that spans multiple
lines.`;
console.log(multiLine);
7. String Immutability

Remember that strings are immutable. Modifying a string creates a new string instead of changing the original.

Example:
let myString = "Hello";
myString[0] = "h"; // This will not change the original string
console.log(myString); // Output: Hello
8. Best Practices
  • Use let and const: Always use let or const to declare variables for strings to avoid hoisting issues.
  • Prefer Template Literals: Use template literals for easier string interpolation and multi-line strings.
  • Avoid Global Scope: Avoid using global variables, encapsulate your code in functions or modules.
  • Use meaningful variable names: Use descriptive names for better readability.
9. Advanced String Manipulation
  • Combining Strings

You can combine strings using + or concat() method.

Example:
let str1 = "Hello";
let str2 = "World!";
let combined = str1 + ", " + str2;
console.log(combined); // Output: Hello, World!

let combinedConcat = str1.concat(", ", str2);
console.log(combinedConcat); // Output: Hello, World!
  • Regular Expressions

You can use regular expressions to perform complex string manipulations.

Example:
let myString = "Hello, World!";
let regex = /World/i;
console.log(regex.test(myString)); // Output: true
console.log(myString.replace(regex, "JavaScript")); // Output: Hello, JavaScript!
Example: String Manipulation Function

Here’s a complete example that combines several concepts:

function formatAndGreet(name) {
    let greeting = `Hello, ${name.trim().toUpperCase()}!`;
    return greeting;
}

let userName = "   john   ";
console.log(formatAndGreet(userName)); // Output: Hello, JOHN!
Conclusion

Strings in JavaScript are versatile and powerful for manipulating text. Mastering string methods and best practices will significantly enhance your coding skills.

MethodDescription
lengthGets the length of the string
toUpperCase()Converts to uppercase
toLowerCase()Converts to lowercase
trim()Removes whitespace from both ends
includes()Checks if a string contains a substring
indexOf()Returns the index of a substring
slice()Extracts part of a string
split()Splits a string into an array
replace()Replaces a substring

Interview Questions:

Here are 20 interview questions about JavaScript strings, complete with answers and explanations:
1. What is a string in JavaScript?

Answer:
A string is a sequence of characters used to represent text in JavaScript. It can be created using single quotes ('), double quotes ("), or backticks (`).

2. How do you find the length of a string?

Answer:
You can find the length of a string using the .length property.

Example:
let str = "Hello, World!";
console.log(str.length); // Output: 13
3. What method would you use to convert a string to uppercase?

Answer:
You can use the .toUpperCase() method.

Example:
let str = "hello";
console.log(str.toUpperCase()); // Output: HELLO
4. How can you check if a string contains a substring?

Answer:
You can use the .includes() method.

Example:
let str = "Hello, World!";
console.log(str.includes("World")); // Output: true
5. What does the trim() method do?

Answer:
The trim() method removes whitespace from both ends of a string.

Example:
let str = "   Hello, World!   ";
console.log(str.trim()); // Output: "Hello, World!"
6. How do you extract a substring from a string?

Answer:
You can extract a substring using the .slice() or .substring() methods.

Example:
let str = "JavaScript";
console.log(str.slice(0, 4)); // Output: "Java"
console.log(str.substring(4, 10)); // Output: "Script"
7. What is the difference between slice() and substring()?

Answer:

  • slice() can accept negative indices, while substring() does not.
  • slice(start, end) extracts characters from start to end - 1, while substring(start, end) swaps start and end if start > end.
8. How would you replace a substring in a string?

Answer:
You can use the .replace() method.

Example:
let str = "Hello, World!";
let newStr = str.replace("World", "JavaScript");
console.log(newStr); // Output: "Hello, JavaScript!"
9. What method would you use to split a string into an array?

Answer:
You can use the .split() method.

Example:
let str = "apple,banana,cherry";
let fruits = str.split(",");
console.log(fruits); // Output: ["apple", "banana", "cherry"]
10. How can you check the position of a character in a string?

Answer:
You can use the .indexOf() method.

Example:
let str = "Hello, World!";
console.log(str.indexOf("o")); // Output: 4
11. What does the lastIndexOf() method do?

Answer:
The lastIndexOf() method returns the last index at which a specified value can be found in a string.

Example:
let str = "Hello, Hello!";
console.log(str.lastIndexOf("Hello")); // Output: 7
12. How can you convert a string to lowercase?

Answer:
You can use the .toLowerCase() method.

Example:
let str = "Hello, World!";
console.log(str.toLowerCase()); // Output: "hello, world!"
13. What are template literals in JavaScript?

Answer:
Template literals are string literals that allow embedded expressions, multi-line strings, and are enclosed by backticks (`)

Example:
let name = "Alice";
let greeting = `Hello, ${name}!`;
console.log(greeting); // Output: "Hello, Alice!"
14. How do you concatenate two strings?

Answer:
You can concatenate strings using the + operator or the .concat() method.

Example:
let str1 = "Hello";
let str2 = "World!";
let combined = str1 + ", " + str2;
console.log(combined); // Output: "Hello, World!"

let combinedConcat = str1.concat(", ", str2);
console.log(combinedConcat); // Output: "Hello, World!"
15. What will be the output of typeof "Hello"?

Answer:
The output will be "string".

Example:
console.log(typeof "Hello"); // Output: "string"
16. How can you create a multi-line string?

Answer:
You can create a multi-line string using template literals (backticks)

Example:
let multiLine = `This is a string
that spans multiple
lines.`;
console.log(multiLine);
17. Can strings be modified directly? Why or why not?

Answer:
No, strings cannot be modified directly because they are immutable. Any modification creates a new string.

Example:
let str = "Hello";
str[0] = "h"; // This will not change the original string
console.log(str); // Output: "Hello"
18. What does the charAt() method do?

Answer:
The charAt() method returns the character at a specified index in a string.

Example:
let str = "JavaScript";
console.log(str.charAt(0)); // Output: "J"
19. How do you determine if a string starts with a specific substring?

Answer:
You can use the .startsWith() method.

Example:
let str = "Hello, World!";
console.log(str.startsWith("Hello")); // Output: true
20. How can you determine if a string ends with a specific substring?

Answer:
You can use the .endsWith() method.

Example:
let str = "Hello, World!";
console.log(str.endsWith("World!")); // Output: true