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

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

    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)
    

    You should check out Is there a RegExp.escape function in Javascript? if the possibility exists that regexp control characters appear in the string.

提交回复
热议问题