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

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

    Here is a minor improvement to CMS's solution:

    if(!String.prototype.startsWith){
        String.prototype.startsWith = function (str) {
            return !this.indexOf(str);
        }
    }
    
    "Hello World!".startsWith("He"); // true
    
     var data = "Hello world";
     var input = 'He';
     data.startsWith(input); // true
    

    Checking whether the function already exists in case a future browser implements it in native code or if it is implemented by another library. For example, the Prototype Library implements this function already.

    Using ! is slightly faster and more concise than === 0 though not as readable.

提交回复
热议问题