Новости из мира ПК
5 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд

Starts with javascript

How to check if a string “StartsWith” another string?

How would I write the equivalent of C#’s String.StartsWith in JavaScript?

Note: This is an old question, and as pointed out in the comments ECMAScript 2015 (ES6) introduced the .startsWith method. However, at the time of writing this update (2015) browser support is far from complete.

18 Answers 18

You can use ECMAScript 6’s String.prototype.startsWith() method, but it’s not yet supported in all browsers. You’ll want to use a shim/polyfill to add it on browsers that don’t support it. Creating an implementation that complies with all the details laid out in the spec is a little complicated. If you want a faithful shim, use either:

  • Matthias Bynens’s String.prototype.startsWith shim, or
  • The es6-shim, which shims as much of the ES6 spec as possible, including String.prototype.startsWith .

Once you’ve shimmed the method (or if you’re only supporting browsers and JavaScript engines that already have it), you can use it like this:

Another alternative with .lastIndexOf :

This looks backwards through haystack for an occurrence of needle starting from index 0 of haystack . In other words, it only checks if haystack starts with needle .

In principle, this should have performance advantages over some other approaches:

  • It doesn’t search the entire haystack .
  • It doesn’t create a new temporary string and then immediately discard it.

Without a helper function, just using regex’s .test method:

To do this with a dynamic string rather than a hardcoded one (assuming that the string will not contain any regexp control characters):

You should check out Is there a RegExp.escape function in Javascript? if the possibility exists that regexp control characters appear in the string.

Best solution:

And here is endsWith if you need that too:

For those that prefer to prototype it into String:


I just wanted to add my opinion about this.

I think we can just use like this:

Here is a minor improvement to CMS’s solution:

Checking whether the function already exists in case a future browser implements it in native code or if it is implemented by another library. For example, the Prototype Library implements this function already.

Using ! is slightly faster and more concise than === 0 though not as readable.

Читать еще:  Java mission control что это

Also check out underscore.string.js. It comes with a bunch of useful string testing and manipulation methods, including a startsWith method. From the docs:

startsWith _.startsWith(string, starts)

This method checks whether string starts with starts .

I recently asked myself the same question.
There are multiple possible solutions, here are 3 valid ones:

  • s.indexOf(starter) === 0
  • s.substr(0,starter.length) === starter
  • s.lastIndexOf(starter, 0) === 0 (added after seeing Mark Byers’s answer)

I haven’t come across the last solution which makes uses of a loop.
Surprisingly this solution outperforms the first 3 by a significant margin.
Here is the jsperf test I performed to reach this conclusion:

ps: ecmascript 6 (harmony) introduces a native startsWith method for strings.
Just think how much time would have been saved if they had thought of including this much needed method in the initial version itself.


As Steve pointed out (the first comment on this answer), the above custom function will throw an error if the given prefix is shorter than the whole string. He has fixed that and added a loop optimization which can be viewed at

Note that there are 2 loop optimizations which Steve included, the first of the two showed better performance, thus I will post that code below:

Since this is so popular I think it is worth pointing out that there is an implementation for this method in ECMA 6 and in preparation for that one should use the ‘official’ polyfill in order to prevent future problems and tears.

Luckily the experts at Mozilla provide us with one:

Please note that this has the advantage of getting gracefully ignored on transition to ECMA 6.

The best performant solution is to stop using library calls and just recognize that you’re working with two arrays. A hand-rolled implementation is both short and also faster than every other solution I’ve seen here.

For performance comparisons (success and failure), see (Make sure you check for later versions that may have trumped mine.)

I just learned about this string library:

Include the js file and then use the S variable like this:

It can also be used in NodeJS by installing it:

Then requiring it as the S variable:

The web page also has links to alternate string libraries, if this one doesn’t take your fancy.

  1. The question is a bit old, but I wanted to write this answer to show you some benchmarks I made based on all the answers provided here and the jsperf shared by Jim Buck.

I basically needed a fast way to find if a long needle is within a long haystack and they are very similar except for the last characters.

Here’s the code I have written which for each function (splice, substring, startsWith, etc.) tests both when they return false and true against a haystack string ( nestedString ) of 1.000.0001 characters and a falsy or truthy needle string of 1.000.000 chars ( testParentStringFalse and testParentStringTrue , respectively):

I runned this benchmark test on Chrome 75, Firefox 67, Safari 12 and Opera 62.

I haven’t included Edge and IE because I do not have them on this machine, but if someone of you wants to run the script against Edge and at least IE 9 and share the output here I would be very curious to see the results.

Just remember that you need to recreate the 3 long strings and save the script in a file which you then open in your browser as copy/paste on the browser’s console will block it as each string’s length is >= 1.000.000).

Here are the outputs:

Chrome 75 ( substring wins):

Firefox 67 ( indexOf wins):

Safari 12 ( slice wins for false results, startsWith wins for true results, also Safari is the fastest in terms of total time to to execute the whole test):

Opera 62 ( substring wins. Results are similar to Chrome and I am not surprised as Opera is based on Chromium and Blink):

It turns out every browser has its own implementation details (apart Opera, which is based on Chrome’s Chromium and Blink).

String startsWith() Method in JavaScript

If you ever need to check if a string begins with another string, use ES6’s startsWith method. I really like this method because intuitively it’s so comprehensive. Even if you don’t know have any tech background, just by reading the code, you can more easily deduce what’s happening in comparison to indexOf

I really like the direction JavaScript is going. Not just introducing all these helpful methods, but evolving the language to be more human readable. This is how we make tech more accessible. Make it easier to learn. Love it!

startsWith () Parameters

The startsWith method accepts 2 parameters:

1. Search Value

This is a required field. Here is where you pass your search value. This can be a single character or longer. Let’s see some examples

Single Character

Multiple Characters

Multiple Words

Entire String

Exceeding String’s Length

2. Starting Index

So by default, your starting index is going to be 0 . But with this parameter, you can make it start at a different starting position. Let’s take a look at a few examples.

Default Index (0)

Start at the 1st index

For those new to programming. Please note that JavaScript is zero-based. Meaning the count begins at 0 . So the first character is at 0 index, the second character is at 1 index

Start at the 2nd index

Following our zero-based counting, the 2nd index is equal to the 3rd character.

Negative Starting Index

So negative index won’t work. I was trying to be clever to test if negative index would work similarly like slice() where if you pass a negative index, it would be the last character. Proof again, don’t think you can outsmart JavaScript

I guess that’s what endsWith is for. I’ll cover this in a future tidbit

Case Sensitive

One important thing to keep in mind is the startWith method is case sensitive.

Browser Support

This is supported by all modern browser. Except for …. I’m sure you guessed it — no Internet Explorer . You will need to use a Polyfill or a compiler like Babel.

Community Inputs

What other way do you know of checking if a string begins with something?

This is the question I asked the community. Got some really good ones. Let’s take a look

Using Search

Using Regex

Using Bracket

If you’re just checking for one singular character, you can try this. But note when you have more than character (ie. hel), this method won’t work.

Performance Check

@gwardwell : Here’s one such test (found on JSPerf, I d >indexOf blows startsWith away.

Ссылка на основную публикацию