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

后端 未结 19 1328
我在风中等你
我在风中等你 2020-11-21 22:35

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

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

haystack.startsWith(needle)          


        
相关标签:
19条回答
  • 2020-11-21 23:01

    You can also return all members of an array that start with a string by creating your own prototype / extension to the the array prototype, aka

    Array.prototype.mySearch = function (target) {
        if (typeof String.prototype.startsWith != 'function') {
            String.prototype.startsWith = function (str){
            return this.slice(0, str.length) == str;
          };
        }
        var retValues = [];
        for (var i = 0; i < this.length; i++) {
            if (this[i].startsWith(target)) { retValues.push(this[i]); }
        }
        return retValues;
    };
    

    And to use it:

    var myArray = ['Hello', 'Helium', 'Hideout', 'Hamster'];
    var myResult = myArray.mySearch('Hel');
    // result -> Hello, Helium
    
    0 讨论(0)
  • 2020-11-21 23:02

    I am not sure for javascript but in typescript i did something like

    var str = "something";
    (<String>str).startsWith("some");
    

    I guess it should work on js too. I hope it helps!

    0 讨论(0)
  • 2020-11-21 23:04

    I just wanted to add my opinion about this.

    I 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
    }
    
    0 讨论(0)
  • 2020-11-21 23:04

    The string object has methods like startsWith, endsWith and includes methods.

    • StartsWith checks whether the given string starts at the beginning or not.

    • endsWith checks whether the given string is at the end or not.

    • includes checks whether the given string is present at any part or not.

    You can find the complete difference between these three in the bellow youtube video

    https://www.youtube.com/watch?v=E-hyeSwg0PA

    0 讨论(0)
  • 2020-11-21 23:08

    Here is a minor improvement to CMS's solution:

    if(!String.prototype.startsWith){
        String.prototype.startsWith = function (str) {
            return !this.indexOf(str);
        }
    }
    
    "Hello World!".startsWith("He"); // true
    
     var data = "Hello world";
     var input = 'He';
     data.startsWith(input); // true
    

    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.

    0 讨论(0)
  • 2020-11-21 23:08

    Based on the answers here, this is the version I am now using, as it seems to give the best performance based on JSPerf testing (and is functionally complete as far as I can tell).

    if(typeof String.prototype.startsWith != 'function'){
        String.prototype.startsWith = function(str){
            if(str == null) return false;
            var i = str.length;
            if(this.length < i) return false;
            for(--i; (i >= 0) && (this[i] === str[i]); --i) continue;
            return i < 0;
        }
    }
    

    This was based on startsWith2 from here: http://jsperf.com/startswith2/6. I added a small tweak for a tiny performance improvement, and have since also added a check for the comparison string being null or undefined, and converted it to add to the String prototype using the technique in CMS's answer.

    Note that this implementation doesn't support the "position" parameter which is mentioned in this Mozilla Developer Network page, but that doesn't seem to be part of the ECMAScript proposal anyway.

    0 讨论(0)
提交回复
热议问题