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

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

问题描述

我如何编写相应的C#的 字符串。 JavaScript中的StartsWith

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() 方法,但尚未在所有浏览器中受支持。您将需要使用填充/填充将其添加到不支持它的浏览器上。创建符合所有详细信息的实现规范有点复杂,这个答案中定义的版本不会这样做;如果你想要一个忠诚的垫片,请使用:

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, and the version defined in this answer won't do; 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:

"Hello World!".startsWith("He"); // true

var haystack = "Hello world";
var prefix = 'orl';
haystack.startsWith(prefix); // false

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

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