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

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

    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.

提交回复
热议问题