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

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

    If you are working with startsWith() and endsWith() then you have to be careful about leading spaces. Here is a complete example:

    var str1 = " Your String Value Here.!! "; // Starts & ends with spaces    
    if (str1.startsWith("Your")) { }  // returns FALSE due to the leading spaces…
    if (str1.endsWith("Here.!!")) { } // returns FALSE due to trailing spaces…
    
    var str2 = str1.trim(); // Removes all spaces (and other white-space) from start and end of `str1`.
    if (str2.startsWith("Your")) { }  // returns TRUE
    if (str2.endsWith("Here.!!")) { } // returns TRUE
    

提交回复
热议问题