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

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

提交回复
热议问题