javascript tutorial - [5 Solutions] string with another string ? - javascript - java script - javascript array



Problem:

How to write the equivalent of C#'s String.StartsWith in JavaScript?

var haystack = 'hello world';
var needle = 'he';
//haystack.startsWith(needle) == true
click below button to copy the code. By JavaScript tutorial team

Solution 1:

We 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, and the version defined in this answer won't do; if we want a faithful shim, use either:

  • 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), we can use it like this:
"Hello World!".startsWith("He"); // true

var haystack = "Hello world";
var prefix = 'orl';
haystack.startsWith(prefix); // fals
click below button to copy the code. By JavaScript tutorial team

Solution 2:

Another alternative with lastIndexOf : haystack.lastIndexOf(needle, 0) === 0 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.

Solution 3:

	data.substring(0, input.length) === input
click below button to copy the code. By JavaScript tutorial team

Solution 4:

Without a helper function, just using regex's .test method: /^He/.test('Hello world') To do this with a dynamic string rather than a hardcoded one (assuming that the string will not contain any regexp control characters): new RegExp('^' + needle).test(haystack) If the possibility exists that regexp control characters appear in the string.

Solution 5:

We just wanted to add my opinion about this.

We think we can just use like this:

var haystack = 'hello world';
var needle = 'he';

if (haystack.indexOf(needle) == 0) {
  // Code if string starts with this substring
}
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - string with another string?