How do I check if a string starts with a specific substring in JavaScript?
Rashid D
rashid d profile pic

In JavaScript, there are multiple approaches to check if a string starts with a specific substring. Here's a step-by-step explanation of different methods you can use: 1. Using thestartsWith() method: - ThestartsWith() method checks if a string starts with a specified substring and returnstrue orfalse accordingly.

1
2
3
4
5
6

   const str = 'Hello, World!';
   const substring = 'Hello';

   const startsWithSubstring = str.startsWith(substring);
   

In this example,startsWith() is used to check if the stringstr starts with the substring'Hello'. The variablestartsWithSubstring will betrue if it does. 2. Using theindexOf() method: - TheindexOf() method returns the index of the first occurrence of a substring within a string. By checking if the returned index is0, you can determine if the string starts with the specified substring.

1
2
3
4
5
6

   const str = 'Hello, World!';
   const substring = 'Hello';

   const startsWithSubstring = str.indexOf(substring) === 0;
   

In this example,indexOf() is used to check if the substring'Hello' is at index0 of the stringstr. If it is, the variablestartsWithSubstring will betrue. 3. Using regular expressions: - Regular expressions can be used to test if a string matches a pattern. By using the^ symbol at the start of the pattern, you can match the substring only at the beginning of the string.

1
2
3
4
5
6

   const str = 'Hello, World!';
   const substring = 'Hello';

   const startsWithSubstring = new RegExp(`^${substring}`).test(str);
   

Here, a regular expression is created with the pattern^Hello, which matches the substring'Hello' only at the beginning of the string. Thetest() method is then used to check if the stringstr matches the pattern, resulting instartsWithSubstring beingtrue if it does. Note: The examples provided assume you are checking for exact matches at the beginning of the string. If you need case-insensitive checks or want to check for a substring position other than the start, you can modify the methods accordingly. Choose the method that best suits your specific use case. Consider the requirements of your application and handle potential edge cases to ensure accurate substring matching.