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

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

    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:

    https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith

    if (!String.prototype.startsWith) {
        String.prototype.startsWith = function(searchString, position) {
            position = position || 0;
            return this.indexOf(searchString, position) === position;
        };
    }
    

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

提交回复
热议问题