gpt4 book ai didi

javascript - 如何检查一个字符串 "StartsWith"是否是另一个字符串?

转载 作者:IT老高 更新时间:2023-10-28 11:10:19 32 4
gpt4 key购买 nike

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

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

haystack.startsWith(needle) == true

注意:这是一个老问题,正如评论中指出的那样,ECMAScript 2015 (ES6) 引入了 .startsWith方法。但是,在撰写此更新 (2015) browser support is far from complete 时.

最佳答案

您可以使用 ECMAScript 6 的 String.prototype.startsWith()方法。它是 supported in all major browsers .但是,如果您想在不受支持的浏览器中使用它,您需要使用 shim/polyfill 将其添加到这些浏览器上。创建符合 all the details laid out in the spec 的实现有点复杂。如果您想要一个忠实的垫片,请使用:

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

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

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

关于javascript - 如何检查一个字符串 "StartsWith"是否是另一个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/646628/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com