Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

javascript - 如何检查字符串“ StartsWith”是否为另一个字符串?(How to check if a string “StartsWith” another string?)

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

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

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

haystack.startsWith(needle) == true

Note: This is an old question, and as pointed out in the comments ECMAScript 2015 (ES6) introduced the .startsWith method.

(注意:这是一个古老的问题,正如注释中指出的那样,ECMAScript 2015(ES6)引入了.startsWith方法。)

However, at the time of writing this update (2015) browser support is far from complete .

(但是,在撰写此更新(2015)时, 浏览器支持还远远没有完成 。)

  ask by translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use ECMAScript 6's String.prototype.startsWith() method, but it's not yet supported in all browsers .

(您可以使用ECMAScript 6的String.prototype.startsWith()方法,但并非所有浏览器都支持该方法 。)

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:

(如果您想要忠实的垫片,请使用以下任一方法:)

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:

(对方法进行填充后(或者如果您仅支持已拥有该方法的浏览器和JavaScript引擎),则可以按以下方式使用它:)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...