且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查字符串“StartsWith"是否正确另一个字符串?

更新时间:2022-11-17 13:53:22

您可以使用 ECMAScript 6 的 String.prototype.startsWith() 方法,但它是 尚未在所有浏览器中支持.您需要使用 shim/polyfill 将其添加到不支持它的浏览器上.创建一个符合 所有细节的实现规范 有点复杂.如果您想要一个忠实的垫片,请使用:

You can use ECMAScript 6's String.prototype.startsWith() method, but it's not yet supported in all browsers. You'll want to use a shim/polyfill to add it on browsers that don't support it. Creating an implementation that complies with all the details laid out in the spec is a little complicated. If you want a faithful shim, use either:

  • Matthias Bynens's String.prototype.startsWith shim, or
  • The es6-shim, which shims as much of the ES6 spec as possible, including String.prototype.startsWith.

一旦你对方法进行了填充(或者如果你只支持已经拥有它的浏览器和 JavaScript 引擎),你可以像这样使用它:

Once you've shimmed the method (or if you're only supporting browsers and JavaScript engines that already have it), you can use it like this:

   console.log("Hello World!".startsWith("He")); // true
    
var haystack = "Hello world";
var prefix = 'orl';
console.log(haystack.startsWith(prefix)); // false