如何检查字符串“StartsWith"是否正确另一个字符串? [英] How to check if a string "StartsWith" another string?

查看:28
本文介绍了如何检查字符串“StartsWith"是否正确另一个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何编写等效于 C# 的 String.StartsWith 在 JavaScript 中?

How would I write the equivalent of C#'s String.StartsWith in JavaScript?

var haystack = 'hello world';
var needle = 'he';

haystack.startsWith(needle) == true

注意:这是一个老问题,正如 ECMAScript 2015 (ES6) 的评论中所指出的,引入了 .startsWith 方法.但是,在撰写此更新时(2015 年)浏览器支持远未完成.

Note: This is an old question, and as pointed out in the comments ECMAScript 2015 (ES6) introduced the .startsWith method. However, at the time of writing this update (2015) browser support is far from complete.

推荐答案

您可以使用 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

这篇关于如何检查字符串“StartsWith"是否正确另一个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆