Specifiy Charaters in a String to Read Javascript
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 equally a single grapheme or multiple characters.
For the purposes of this article, nosotros'll be searching for the letter 'J' at the beginning of the word 'JavaScript':
const word = ' JavaScript ' ; const char = ' J ' ; We'll so use char alongside a few different methods to demonstrate approaches to finding a grapheme at the beginning of a string in JavaScript!
Based on what you're doing, you might want to "extract" part of that string, however mostly we actually need to check if the character(due south) are even in that location to begin with. This ways we'll simply want a Boolean (truthful/false) value back from our methods.
ES6 .startsWith()
Firstly, you're probably here for the "right answer", so allow'southward start with String.image.startsWith, a mildly new String feature introduced in ES2015 / ES6:
const word = ' JavaScript ' ; const char = ' J ' ; word . startsWith ( char ); // truthful This is the most modern and recommended approach. The remaining methods in this article are but for reference and different scenarios.
🕵️♂️ Note: This method isn't supported in Net Explorer, and so you'll need a polyfill and to check the browser compatibility.
indexOf
We can use String.prototype.indexOf to return u.s. the index of the particular character, and so this 1's nice and uncomplicated:
const word = ' JavaScript ' ; const char = ' J ' ; word . indexOf ( char ) === 0 // true However, unlike our good friend .startsWith() you'll find that nosotros have to do something with the render value and using === 0 to ensure that it fits the starting time of our cord.
Of course as well, this method is just checking the offset graphic symbol, yet will still work for multiple characters as it returns the index of the found detail(s).
lastIndexOf
Before .startsWith() arrived, this was the preferred solution as it was more performant.
Using String.prototype.lastIndexOf allows the cord to search faster as it begins at the index of 0. It looks backwards through the string, starting at the first. Therefore this will get to the answer even faster. If information technology finds a match, it won't search the unabridged string.
Similar to .indexOf() we'll also have to check the returned index using === 0:
const word = ' JavaScript ' ; const char = ' J ' ; give-and-take . lastIndexOf ( char , 0 ) === 0 // truthful substring
An oldie only a goodie. Using String.prototype.substring is besides a dainty method for fine-grained string control, every bit it allows us to specify a "search index" via two parameters. Start index, end index.
const word = ' JavaScript ' ; const char = ' J ' ; discussion . substring ( 0 , ane ) === char // true Yous'll detect that this doesn't read besides as the other solutions listed higher up, and let's exist honest we all forget the difference betwixt substring and substr and how to apply them. MDN too considers substr as deprecated, and so I've chosen not to include it nevertheless using information technology in the aforementioned scenario as above volition give the same results.
🎉 Download it free!
Ready to become beyond ForEach? Go confident with advanced methods - Reduce, Notice, Filter, Every, Some and Map.
✅ Success! Check your email, enjoy.
Every bit an actress bonus, we'll too ship y'all some extra goodies across a few extra emails.
string[0] alphabetize
Like to looking up "indexes" in an array, you can as well use the foursquare bracket syntax to lookup each "index" of a string. For example string[0] would render the first item in the string, in the same manner array[0] returns us the first array particular.
With this, nosotros could access the initial character of the string, which requires no office call and should technically exist one of the fastest mechanisms - though it does promote a picayune "oldschool" style code. These days, JavaScript is shifting towards a more functional style, with methods such every bit .startsWith() amid 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, allow's investigate some RegExp!
Congenital into JavaScript is a global function chosen 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
RegExpprototype methods.
Here'south how we can use the ^ character (which means "the beginning of the string") to cheque if our string starts with our graphic symbol:
const word = ' JavaScript ' ; const char = ' J ' ; new RegExp ( `^ ${ char } ` ). test ( word ) // truthful You'll notice I'm using an ES6 string literal and some interpolation here. This is basically the aforementioned as doing new RegExp('^' + char) simply is obviously more crawly, as who likes concatenating strings anymore?
Finally, we could also "hard code" our Regular Expression and use it against .exam() (which returns a Boolean, by the manner):
const word = ' JavaScript ' ; const char = ' J ' ; /^J/ . exam ( word ) // truthful Simply you can see how this would be less appealing.
All-in-all, y'all know startsWith is the way to go, so what're you waiting for?
🏆 Oh, and if you lot'd like to learn even more JavaScript y'all should come up and check out my JavaScript courses. They're the result of ten years of developing and I've put every ounce of knowledge into them, I hope yous find them super helpful for your career!
P.S. Here's a StackBlitz embed with everything inside, so y'all can have a fiddle with it in real-fourth dimension:
Thank you for reading, come check out our Newsletter to stay up to appointment with the latest and greatest in all things spider web.
Source: https://ultimatecourses.com/blog/javascript-string-starts-with-characters
0 Response to "Specifiy Charaters in a String to Read Javascript"
Post a Comment