Open In App

JavaScript String Interview Questions and Answers

Last Updated : 12 Sep, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A JavaScript String is a sequence of characters, typically used to represent text.

  • In JavaScript, there is no character type (Similar to Python and different from C, C++ and Java), so a single character string is used when we need a character.
  • Like Java and Python, strings in JavaScript are immutable

1. How do you create a string in JavaScript?

You create a string by putting text inside single quotes, double quotes, or backticks. Single and double quotes are simple and work the same, while backticks let you add variables or write multiple lines.

Example:

JavaScript
let str1 = 'Hello'; // Simple string with single quotes
let str2 = "World"; // Simple string with double quotes
let str3 = `Hello ${str2}`; // Backticks with variable
let str4 = new String('Hi'); // String object (not recommended)
console.log(str3); 
console.log(str4); 

You can also use the new String() method, but it’s less common because it creates a special object instead of a simple string.

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

The length property tells you how many characters are in a string, including spaces. It’s like counting the letters in a word. Just add .length to the string, and you get a number. For an empty string, it returns 0.

Example:

JavaScript
let str = 'Hello World';
console.log(str.length);
let empty = '';
console.log(empty.length);

3. How can you concatenate two strings in JavaScript?

Concatenation means joining two strings together, like combining "Hello" and "World" to make "Hello World". You can use the + operator to glue strings, the concat() method to merge them, or template literals with backticks for a modern way to combine with variables.

Example:

JavaScript
let str1 = 'Hello';
let str2 = 'World';
let result1 = str1 + ' ' + str2; // Using +
let result2 = str1.concat(' ', str2); // Using concat()
let result3 = `${str1} ${str2}`; 
console.log(result1);

4. What is the difference between == and === when comparing strings in JavaScript?

The == operator checks if two values are equal after converting them to the same type, like turning a string "5" into the number 5. The === operator is stricter and checks both value and type, so "5" and 5 are different. For strings, use === to avoid surprises from type changes.

Example:

JavaScript
console.log('5' == 5); 
console.log('5' === 5);
console.log('hello' === 'hello'); 

5. How do you convert a string to uppercase or lowercase in JavaScript?

To make all letters in a string uppercase (like shouting "HELLO"), use toUpperCase(). For lowercase (like whispering "hello"), use toLowerCase(). These methods create a new string and don’t change the original, great for making text uniform or comparing without caring about case.

Example:

JavaScript
let str = 'Hello World';
console.log(str.toUpperCase()); 
console.log(str.toLowerCase()); 
console.log(str); 

6. How do you extract a part of a string in JavaScript?

You can grab a piece of a string using slice(), substring(), or substr(). These methods let you pick a section by specifying start and end positions. slice() is the most flexible because it can use negative numbers to count from the end, while substring() is simpler but doesn’t allow negatives.

Example:

JavaScript
let str = 'Hello World';
console.log(str.slice(0, 5)); 
console.log(str.substring(0, 5)); 
console.log(str.slice(-5)); 

7. How do you check if a string contains a specific substring in JavaScript?

The includes() method checks if a smaller string (substring) exists inside a bigger string, returning true or false. It’s case-sensitive, meaning "World" and "world" are different. This is handy for searching text, like checking if a word is in a sentence.

Example:

JavaScript
let str = 'Hello World';
console.log(str.includes('World')); 
console.log(str.includes('world')); 

8. How do you replace a substring within a string in JavaScript?

The replace() method swaps the first occurrence of a substring with a new string. For example, you can change "World" to "JavaScript" in "Hello World". It’s case-sensitive and only changes the first match unless you use a special pattern (we’ll cover that later).

Example:

JavaScript
let str = "Hello World";
let newStr = str.replace("World", "JavaScript");
console.log(newStr); 

9. How do you split a string into an array in JavaScript?

The split() method breaks a string into an array of smaller strings based on a separator, like a comma or space. For example, splitting "Hello,World" by a comma gives ['Hello', 'World']. It’s great for turning a list or sentence into pieces you can work with.

Example:

JavaScript
let str = 'Hello,World,JavaScript';
let arr = str.split(','); // Split by comma
console.log(arr); 

10. What is the purpose of the charAt() method in JavaScript?

The charAt() method gives you the character at a specific position (index) in a string, starting from 0. For example, in "Hello", charAt(1) returns "e". If the position doesn’t exist, it returns an empty string.

Example:

JavaScript
let str = 'Hello';
console.log(str.charAt(1)); 
console.log(str.charAt(10)); 

11. How do you pad a string to a certain length in JavaScript?

The padStart() method adds characters (like zeros) to the start of a string until it reaches a desired length, and padEnd() adds them to the end. This is useful for formatting numbers, like making "5" into "005".

Example:

JavaScript
let str = '5';
console.log(str.padStart(3, '0')); 
console.log(str.padEnd(3, '0')); 

12. When is matchAll() preferable to repeated exec loops?

Both matchAll() and repeated exec loops can find all regex matches, but matchAll() is often clearer, safer, and more ergonomic.

  • Cleaner access to groups:matchAll() yields an iterator of full match objects (with capturing and named groups) directly, making code shorter and easier to read.
  • No lastIndex pitfalls: It doesn’t mutate or depend on the regex’s lastIndex, so you avoid hard-to-debug bugs when reusing the same regex or mixing async code.
  • Lazy iteration: Results are produced on demand with for...of/spread, which is memory-friendly for long strings.
  • Stable snapshot: It works off an internal copy of the regex with g, so external changes to the regex don’t affect iteration mid-loop.

13. What does the localeCompare() method do in JavaScript?

The localeCompare() method compares two strings to see which comes first in alphabetical order, based on the user’s language rules. It returns -1 if the first string is before, 0 if they’re equal, or 1 if it’s after. This is great for sorting words correctly.

Example:

JavaScript
let str1 = 'apple';
let str2 = 'banana';
console.log(str1.localeCompare(str2)); 

14. How do you find the index of a substring in a string in JavaScript?

The indexOf() method finds where a substring starts in a string, giving you its position (index). If it’s not found, it returns -1. It’s case-sensitive and starts looking from the beginning.

Example:

JavaScript
let str = 'Hello World';
console.log(str.indexOf('World')); 
console.log(str.indexOf('world')); 

15. What is the difference between slice() and substring()?

Both slice() and substring() cut out a piece of a string, but slice() can use negative numbers to count from the end, like getting the last few letters. substring() treats negatives as 0 and can swap start and end if they’re in the wrong order.

Example:

JavaScript
let str = 'Hello World';
console.log(str.slice(-5)); 
console.log(str.substring(6)); 
console.log(str.substring(11, 6)); 

16. How do you convert a string to an array of characters in JavaScript?

Use split('') to break a string into an array where each letter is an item. For example, "Hello" becomes ['H', 'e', 'l', 'l', 'o']. You can also use the spread operator (...) to do the same thing.

Example:

JavaScript
let str = 'Hello';
let arr1 = str.split('');
let arr2 = [...str];
console.log(arr1); 

17. How do you check if a string starts with a specific substring in JavaScript?

The startsWith() method checks if a string begins with a certain substring, like seeing if "Hello World" starts with "Hello". It returns true or false and is case-sensitive.

Example:

JavaScript
let str = 'Hello World';
console.log(str.startsWith('Hello')); 
console.log(str.startsWith('World')); 

18. How do you check if a string ends with a specific substring in JavaScript?

The endsWith() method checks if a string finishes with a certain substring, like checking if "Hello World" ends with "World". It returns true or false and is case-sensitive.

Example:

JavaScript
let str = 'Hello World';
console.log(str.endsWith('World')); 
console.log(str.endsWith('Hello')); 

19. How do you use template literals in JavaScript?

Template literals use backticks ( ) instead of quotes, letting you add variables with ${} and write strings across multiple lines. They make it easier to create dynamic text, like greetings with someone’s name.

Example:

JavaScript
let name = 'World';
let greeting = `Hello, ${name}!
This is multi-line.`; 
console.log(greeting); 

20. How do you escape special characters in a string in JavaScript?

To use special characters like quotes or backslashes in a string, put a backslash (\) before them. This “escapes” them so they’re treated as regular characters, not code. For example, to include a quote inside a quoted string, use \".

Example:

JavaScript
let str = 'He said, \"Hello World!\"';
console.log(str); 
console.log('Line1\nLine2'); 

21. How do you compare two strings in JavaScript?

Use localeCompare() to compare strings in a way that respects language sorting rules, like putting "apple" before "banana". It returns -1, 0, or 1 based on their order. You can also use === for exact matches.

Example:

JavaScript
let str1 = 'apple';
let str2 = 'banana';
console.log(str1.localeCompare(str2)); 
console.log(str1 === str2); 

22. How do you access characters in a string using bracket notation?

Bracket notation (str[index]) lets you pick a character from a string by its position, starting at 0. For example, str[1] gets the second character. If the position is invalid, it returns undefined.

Example:

JavaScript
let str = 'Hello';
console.log(str[1]); 
console.log(str[10]);

23. How do you convert a string to an array of words in JavaScript?

Use split(' ') to break a string into an array of words by splitting at spaces. For example, "Hello World" becomes ['Hello', 'World']. This is useful for processing sentences.

Example:

JavaScript
let str = 'Hello World';
let words = str.split(' ');
console.log(words); 

24. How do you find the last occurrence of a substring in a string in JavaScript?

The lastIndexOf() method finds the position of the last time a substring appears in a string. If it’s not found, it returns -1. It’s like searching backward.

Example:

JavaScript
let str = 'Hello World Hello';
console.log(str.lastIndexOf('Hello')); 

25. How do you check if a string matches a regular expression in JavaScript?

The match() method checks if a string fits a pattern (regular expression) and returns the matching parts in an array. If there’s no match, it returns null. This is useful for finding specific text patterns.

Example:

JavaScript
let str = 'Hello World';
console.log(str.match(/World/)); 
console.log(str.match(/xyz/)); 

26. How can you reverse a string in JavaScript?

JavaScript provides multiple ways to reverse a string, but the most common method is by converting the string into an array, reversing it, and then joining it back into a string.

  • Step 1 (split): Convert the string into an array of characters using split("").
  • Step 2 (reverse): Use the reverse() method to reverse the array.
  • Step 3 (join): Use join("") to combine the reversed characters back into a string.
JavaScript
let str = "hello";
let reversed = str.split("").reverse().join("");
console.log(reversed); 

27. How do you search for a match in a string using a regular expression in JavaScript?

The search() method looks for a pattern (regular expression) in a string and returns the index where it starts. If not found, it returns -1. It’s like finding where a word begins.

Example:

JavaScript
let str = 'Hello World';
console.log(str.search(/World/)); // Output: 6
console.log(str.search(/xyz/)); // Output: -1

28. How do you replace all occurrences of a substring in a string in JavaScript?

Use replace() with a global pattern (/substring/g) or replaceAll() to change every instance of a substring. For example, change all "Hello"s to "Hi"s in a string.

Example:

JavaScript
let str = 'Hello World Hello';
let newStr = str.replace(/Hello/g, 'Hi');
console.log(newStr); 

29. What is the difference between substring() and substr() in JavaScript?

substring() takes a start and end index to grab a piece of a string, while substr() takes a start index and how many characters to take. substring() is more common; substr() is older and less used now.

Example:

JavaScript
let str = 'Hello World';
console.log(str.substring(6, 11)); 
console.log(str.substr(6, 5)); 

30. How can you count the occurrence of a specific character in a string?

Count how many times a character appears by splitting the string at that character with split() and subtracting 1 from the array length. Or use match() with a pattern to find all matches. Both work, but split() is simpler for single characters.

Example:

JavaScript
let str = 'Hello';
let count = str.split('l').length - 1;
console.log(count); 

31. What is the normalize() method in JavaScript strings and when should it be used?

The normalize() method makes sure different ways of writing the same character (like "é" vs. "e" with an accent mark) are treated the same. It’s useful when comparing text in different languages or cleaning up user input to avoid mismatches.

Example:

JavaScript
let str1 = 'é'; // One character
let str2 = 'e\u0301'; // Two characters (e + accent)
console.log(str1.normalize('NFC') === str2.normalize('NFC')); 

32. How do you convert a string into a URL slug?

A URL slug is a web-friendly string, like "javascript-tips" instead of "JavaScript Tips!". To make one, lowercase the string, replace spaces and special characters with hyphens, and remove anything that’s not a letter, number, or hyphen.

Example:

JavaScript
let title = 'JavaScript Advanced String Handling!';
let slug = title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
console.log(slug); 

33. How do you perform case-insensitive string comparison?

To compare strings without caring about uppercase or lowercase, convert both to the same case using toLowerCase() or toUpperCase() before checking with ===. This makes "Hello" and "hello" match.

Example:

JavaScript
let str1 = 'hello';
let str2 = 'HELLO';
console.log(str1.toLowerCase() === str2.toLowerCase()); 

34. How do you count the number of words in a string?

To count words, use match() with a pattern that finds sequences of letters or numbers, ignoring spaces and punctuation. The length of the resulting array is the word count. This works well for sentences.

Example:

JavaScript
let sentence = 'Hello world, welcome to JavaScript!';
let wordCount = sentence.match(/\b\w+\b/g).length;
console.log(wordCount); 

35. What are tagged template literals and how do you use them?

Tagged template literals let you process a backtick string with a function. The function gets the text parts and variables separately, so you can customize the output, like adding bold tags around variables. It’s like a super-powered way to format strings.

Example:

JavaScript
function highlight(strings, ...values) {
  return strings.reduce((result, str, i) => `${result}${str}<strong>${values[i] || ''}</strong>`, '');
}
let name = 'World';
console.log(highlight`Hello, ${name}!`); 

36. How do you remove all non-alphanumeric characters from a string?

To keep only letters and numbers, use replace() with a pattern that targets anything that’s not a letter or number ([^a-zA-Z0-9]) and replace it with nothing. This cleans up messy strings.

Example:

JavaScript
let str = 'Hello, World! 123.';
let cleaned = str.replace(/[^a-zA-Z0-9]/g, '');
console.log(cleaned); 

37. How can you encode and decode HTML characters in a string?

Use encodeURIComponent() to turn special characters into a safe format for URLs or HTML, and decodeURIComponent() to turn them back. This helps when handling text that might break web pages.

Example:

JavaScript
let html = '<div class="foo">Bar</div>';
let encoded = encodeURIComponent(html);
console.log(encoded); 
console.log(decodeURIComponent(encoded)); 

38. How do you convert a string to a number and vice versa?

To turn a string like "123" into a number, use parseInt() for whole numbers, parseFloat() for decimals, or the + operator. To turn a number back into a string, use toString() or add it to an empty string.

Example:

JavaScript
let str = '123.45';
let num = parseFloat(str); 
let strBack = num.toString(); 
console.log(num, strBack);

39. How do you find the longest word in a string?

Split the string into words with split(), then use reduce() to keep track of the word with the most letters. This is useful for analyzing text, like finding the biggest word in a sentence.

Example:

JavaScript
let sentence = 'JavaScript is awesome';
let longest = sentence.split(' ').reduce((longest, word) => word.length > longest.length ? word : longest, '');
console.log(longest); 

40. How do you implement a function to check if a string is a palindrome?

A palindrome is a word that reads the same backward, like "racecar". Clean the string by removing spaces and punctuation and making it lowercase, then compare it to its reverse to see if they match.

Example:

JavaScript
function isPalindrome(str) {
  let cleaned = str.replace(/[^A-Za-z0-9]/g, '').toLowerCase();
  return cleaned === cleaned.split('').reverse().join('');
}
console.log(isPalindrome('A man, a plan, a canal, Panama')); 

Strings in JavaScript
Visit Course explore course icon