- JavaScript Program to Check Whether a String Starts and Ends With Certain Characters
- Example 1: Check String Using Built-in Methods
- Example 2: Check The String Using Regex
- JavaScript String startsWith()
- See Also:
- Syntax
- Parameters
- Return Value
- Related Pages
- Browser Support
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- String.prototype.startsWith()
- Try it
- Syntax
- Parameters
- Return value
- Exceptions
- Description
- Examples
- Using startsWith()
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- JavaScript: Check if String Starts with Substring
- Check if String Starts with Another String with startsWith()
- Check if String Starts with Another String with Regular Expressions
- Conclusion
- Ways to check if a String starts with specific characters
- ES6 .startsWith()
- indexOf
- lastIndexOf
- substring
- Free eBook
- string[0] index
- Regular Expressions
- Learn JavaScript the right way.
JavaScript Program to Check Whether a String Starts and Ends With Certain Characters
To understand this example, you should have the knowledge of the following JavaScript programming topics:
Example 1: Check String Using Built-in Methods
// program to check if a string starts with 'S' and ends with 'G' function checkString(str) < // check if the string starts with S and ends with G if(str.startsWith('S') && str.endsWith('G')) < console.log('The string starts with S and ends with G'); >else if(str.startsWith('S')) < console.log('The string starts with S but does not end with G'); >else if(str.endsWith('G')) < console.log('The string starts does not with S but end with G'); >else < console.log('The string does not start with S and does not end with G'); >> // take input let string = prompt('Enter a string: '); checkString(string);
Enter a string: String The string starts with S but does not end with G
In the above program, the two methods startsWith() and endsWith() are used.
- The startsWith() method checks if the string starts with the particular string.
- The endsWith() method checks if the string ends with the particular string.
The above program does not check for lowercase letters. Hence, here G and g are different.
You could also check if the above character starts with S or s and ends with G or g.
str.startsWith('S') || str.startsWith('s') && str.endsWith('G') || str.endsWith('g');
Example 2: Check The String Using Regex
// program to check if a string starts with 'S' and ends with 'G' function checkString(str) < // check if the string starts with S and ends with G if( /^S/i.test(str) && /G$/i.test(str)) < console.log('The string starts with S and ends with G'); >else if(/^S/i.test(str)) < console.log('The string starts with S but does not ends with G'); >else if(/G$/i.test(str)) < console.log('The string starts does not with S but ends with G'); >else < console.log('The string does not start with S and does not end with G'); >> // for loop to show different scenario for (let i = 0; i < 3; i++) < // take input const string = prompt('Enter a string: '); checkString(string); >
Enter a string: String The string starts with S and ends with G Enter a string: string The string starts with S and ends with G Enter a string: JavaScript The string does not start with S and does not end with G
In the above program, a regular expression (RegEx) is used with the test() method to check if the string starts with S and ends with G.
- The /^S/i pattern checks if the string is S or s. Here, i denotes that the string is case-insensitive. Hence, S and s are considered the same.
- The /G$/i patterns checks if the string is G or g.
- The if. else. if statement is used to check the conditions and display the outcome accordingly.
- The for loop is used to take different inputs from the user to show different cases.
JavaScript String startsWith()
The startsWith() method returns true if a string starts with a specified string.
Otherwise it returns false .
The startsWith() method is case sensitive.
See Also:
Syntax
Parameters
Parameter | Description |
searchValue | Required. The string to search for. |
start | Optional. Start position. Default is 0. |
Return Value
Type | Description |
A boolean | Returns true if the string starts with the value. Otherwise it returns false . |
Related Pages
Browser Support
startsWith() is an ECMAScript6 (ES6) feature.
ES6 (JavaScript 2015) is supported in all modern browsers:
Chrome | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes |
startsWith() is not supported in Internet Explorer 11 (or earlier).
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
String.prototype.startsWith()
The startsWith() method determines whether a string begins with the characters of a specified string, returning true or false as appropriate.
Try it
Syntax
startsWith(searchString) startsWith(searchString, position)
Parameters
The characters to be searched for at the start of this string. Cannot be a regex. All values that are not regexes are coerced to strings, so omitting it or passing undefined causes startsWith() to search for the string «undefined» , which is rarely what you want.
The start position at which searchString is expected to be found (the index of searchString ‘s first character). Defaults to 0 .
Return value
true if the given characters are found at the beginning of the string, including when searchString is an empty string; otherwise, false .
Exceptions
Description
This method lets you determine whether or not a string begins with another string. This method is case-sensitive.
Examples
Using startsWith()
const str = "To be, or not to be, that is the question."; console.log(str.startsWith("To be")); // true console.log(str.startsWith("not to be")); // false console.log(str.startsWith("not to be", 10)); // true
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Apr 6, 2023 by MDN contributors.
Your blueprint for a better internet.
JavaScript: Check if String Starts with Substring
In this tutorial, we’ll take a look at how to check if a string starts with a substring in JavaScript.
This is easily achieved either through the startsWith() method, or regular expressions.
Check if String Starts with Another String with startsWith()
The startsWith(searchString[, position]) method returns a boolean which indicates whether a string begins with the characters of a specified searchString . Optionally we can also use the position argument to specify the position of the string at which to begin searching.
const str = "This is an example for startsWith() method"; console.log(str.startsWith("This")); // true console.log(str.startsWith("is", 2)); // true
In the first example, we are checking if the string str starts with «This» .
In the second example, we are checking if str starts with «is» , if we are starting our search from index 2 (i.e, 3rd character).
Check if String Starts with Another String with Regular Expressions
Regular Expressions are really powerful, and allow us to match various patterns. This is a great use-case for them, since we’re essentially checking for a pattern — if a string starts with a substring.
The regexObj.test(reg) method tries to match the specified regular expression reg to the original string and returns a boolean value which indicates if a match was found:
const str = "hello world"; const regEx = /^he/; console.log(regEx.test(str)); // true
In this approach, we are checking whether the pattern regEx occurs in the string str . The ^ meta character represents that the specified pattern he must be at the start of a line. Thus, the regular expression — /^he/ checks if the specified line starts with the substring he .
Conclusion
In this tutorial, we’ve taken a look at how to check if a string starts with a substring in vanilla JavaScript, using the startsWith() method, as well as Regular Expressions.
Ways to check if a String starts with specific characters
The most complete guide to learning JavaScript ever built.
Trusted by 82,951 students .
Like all things JavaScript, there are many ways to accomplish the same task. Here we’ll dive into the various ways to check if a JavaScript string starts with something, such as a single character or multiple characters.
For the purposes of this article, we’ll be searching for the letter ‘J’ at the beginning of the word ‘JavaScript’ :
const word = 'JavaScript'; const char = 'J';
We’ll then use char alongside a few different methods to demonstrate approaches to finding a character at the beginning of a string in JavaScript!
Based on what you’re doing, you might want to “extract” part of that string, however more often than not we actually need to check if the character(s) are even there to begin with. This means we’ll simply want a Boolean (true/false) value back from our methods.
ES6 .startsWith()
Firstly, you’re probably here for the “correct answer”, so let’s start with String.prototype.startsWith , a mildly new String feature introduced in ES2015 / ES6:
const word = 'JavaScript'; const char = 'J'; word.startsWith(char); // true
This is the most modern and recommended approach. The remaining methods in this article are simply for reference and different scenarios.
🕵️♂️ Note: This method isn’t supported in Internet Explorer, so you’ll need a polyfill and to check the browser compatibility.
indexOf
We can use String.prototype.indexOf to return us the index of the particular character, so this one’s nice and simple:
const word = 'JavaScript'; const char = 'J'; word.indexOf(char) === 0 // true
However, unlike our good friend .startsWith() you’ll notice that we have to do something with the return value and using === 0 to ensure that it fits the beginning of our string.
Of course as well, this method is just checking the first character, however will still work for multiple characters as it returns the index of the found item(s).
lastIndexOf
Before .startsWith() arrived, this was the preferred solution as it was more performant.
Using String.prototype.lastIndexOf allows the string to search faster as it begins at the index of 0 . It looks backwards through the string, starting at the beginning. Therefore this will get to the answer even faster. If it finds a match, it won’t search the entire string.
Similar to .indexOf() we’ll also have to check the returned index using === 0 :
const word = 'JavaScript'; const char = 'J'; word.lastIndexOf(char, 0) === 0 // true
substring
An oldie but a goodie. Using String.prototype.substring is also a nice method for fine-grained string control, as it allows us to specify a “search index” via two parameters. Start index, end index.
const word = 'JavaScript'; const char = 'J'; word.substring(0, 1) === char // true
You’ll notice that this doesn’t read as well as the other solutions listed above, and let’s be honest we all forget the difference between substring and substr and how to use them. MDN also considers substr as deprecated, so I’ve chosen not to include it however using it in the same scenario as above will give the same results.
Free eBook
Directives, simple right? Wrong! On the outside they look simple, but even skilled Angular devs haven’t grasped every concept in this eBook.
- Observables and Async Pipe
- Identity Checking and Performance
- Web Components syntax
- and Observable Composition
- Advanced Rendering Patterns
- Setters and Getters for Styles and Class Bindings
That went smoothly, check your email.
string[0] index
Similar to looking up “indexes” in an array, you can also use the square bracket syntax to lookup each “index” of a string. For example string[0] would return the first item in the string, in the same way array[0] returns us the first array item.
With this, we could access the initial character of the string, which requires no function call and should technically be one of the fastest mechanisms — though it does promote a little “oldschool” style code. These days, JavaScript is shifting towards a more functional style, with methods such as .startsWith() amongst other utilities.
Here’s using the index lookup syntax:
const word = 'JavaScript'; const char = 'J'; word[0] === char // true
Regular Expressions
I love Regular Expressions (why, I hear you ask?!). I don’t know, they’re just great and make me feel like a “proper coder”. Nevertheless, let’s investigate some RegExp!
Built into JavaScript is a global function called RegExp , which allows us to dynamically construct a Regular Expression.
Check out my in-depth guide to Regular Expression matching for more details on some RegExp prototype methods.
Here’s how we can use the ^ character (which means “the beginning of the string”) to check if our string starts with our character:
const word = 'JavaScript'; const char = 'J'; new RegExp(`^$char>`).test(word) // true
You’ll notice I’m using an ES6 string literal and some interpolation here. This is basically the same as doing new RegExp(‘^’ + char) but is obviously more awesome, as who likes concatenating strings anymore?
Finally, we could also “hard code” our Regular Expression and use it against .test() (which returns a Boolean , by the way):
const word = 'JavaScript'; const char = 'J'; /^J/.test(word) // true
But you can see how this would be less appealing.
All-in-all, you know startsWith is the way to go, so what’re you waiting for?
🏆 Oh, and if you’d like to learn even more JavaScript you should come and check out my JavaScript courses. They’re the result of 10 years of developing and I’ve put every ounce of knowledge into them, I hope you find them super helpful for your career!
P.S. Here’s a StackBlitz embed with everything inside, so you can have a fiddle with it in real-time:
Thanks for reading, come check out our Newsletter to stay up to date with the latest and greatest in all things web.
Learn JavaScript the right way.
The most complete guide to learning JavaScript ever built.
Trusted by 82,951 students .