How to check String that begins with a specific character

Tram Ho

Hi hello, me again, continuing the topic with JavaScript, namely working with strings today, we will discuss the topic “How to test String starts with a specific character “. At the beginning of the story, let’s scroll down to find out (go)

Throughout today’s article, we will solve the problem “How to check if the word J has to start in a JavaScript string or not”

Method 1. Use the String.prototype.startsWith() method String.prototype.startsWith()

Definitely the easiest to understand and use method, so without much introduction, startsWith() returns true if match and false otherwise.

However, please note that this method does not support IE, so to work perfectly on many browsers we need to use the following polyfill.

Method 2. Using indexOf ()

This method returns the position of the character in the string, so if you want to know if the character J is at the beginning of the string or not, we have the following

Method 3. Using lastIndexOf ()

lastIndexOf() takes 2 parameters, which are the keyword to be searched for and indexed. So to solve the above problem we can do the following

Method 4. Using Substring ()

substring() used to truncate strings, with input parameters including starting position and ending position. So we can use this function to cut out the first character and compare it with the desired character

Method 5. Use string index

Similar to arrays, with strings you can also get the first element using the following syntax

Or in a cooler way

Method 6. Use regex

The power of regex is sure that there is no need to introduce much more, in regex there is 1 character to help you check the beginning of the string is ^ . The code will be as follows

Or you can write like this


Above I have introduced some ways to check strings starting with a specified character, if you have any better way, please share with everyone.

If you find a good article, give me +1 upvote. If you like me, please press the follow button for more interesting things. Good luck

Share the news now

Source : Viblo