Compare part of string in JavaScript

后端 未结 7 2063
感动是毒
感动是毒 2020-12-31 01:12

How do I compare a part of a string - for example if I want to compare if string A is part of string B. I would like to find out this: When string A = \"abcd\"

7条回答
  •  南方客
    南方客 (楼主)
    2020-12-31 01:48

    Using indexOf or match is unnecessarily slow if you are dealing with large strings and you only need to validate the beginning of the string. A better solution is to use startsWith() or its equivalent function-- from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith:

    if (!String.prototype.startsWith) {
        String.prototype.startsWith = function(searchString, position){
          position = position || 0;
          return this.substr(position, searchString.length) === searchString;
      };
    }
    

提交回复
热议问题