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

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

    Best solution:

    function startsWith(str, word) {
        return str.lastIndexOf(word, 0) === 0;
    }
    

    And here is endsWith if you need that too:

    function endsWith(str, word) {
        return str.indexOf(word, str.length - word.length) !== -1;
    }
    

    For those that prefer to prototype it into String:

    String.prototype.startsWith || (String.prototype.startsWith = function(word) {
        return this.lastIndexOf(word, 0) === 0;
    });
    
    String.prototype.endsWith   || (String.prototype.endsWith = function(word) {
        return this.indexOf(word, this.length - word.length) !== -1;
    });
    

    Usage:

    "abc".startsWith("ab")
    true
    "c".ensdWith("c") 
    true
    

    With method:

    startsWith("aaa", "a")
    true
    startsWith("aaa", "ab")
    false
    startsWith("abc", "abc")
    true
    startsWith("abc", "c")
    false
    startsWith("abc", "a")
    true
    startsWith("abc", "ba")
    false
    startsWith("abc", "ab")
    true
    

提交回复
热议问题