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

后端 未结 19 1311
我在风中等你
我在风中等你 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
    

提交回复
热议问题