JavaScript中的endsWith

2023-11-05

如何在JavaScript中检查字符串是否以特定字符结尾?

示例:我有一个字符串

var str = "mystring#";

我想知道该字符串是否以#结尾。 我该如何检查?

  1. JavaScript中是否有endsWith()方法?

  2. 我有一个解决方案是获取字符串的长度并获取最后一个字符并进行检查。

这是最好的方法还是还有其他方法?


#1楼

String.prototype.endWith = function (a) {
    var isExp = a.constructor.name === "RegExp",
    val = this;
    if (isExp === false) {
        a = escape(a);
        val = escape(val);
    } else
        a = a.toString().replace(/(^\/)|(\/$)/g, "");
    return eval("/" + a + "$/.test(val)");
}

// example
var str = "Hello";
alert(str.endWith("lo"));
alert(str.endWith(/l(o|a)/));

#2楼

String.prototype.endsWith = function(str) 
{return (this.match(str+"$")==str)}

String.prototype.startsWith = function(str) 
{return (this.match("^"+str)==str)}

我希望这有帮助

var myStr = “  Earth is a beautiful planet  ”;
var myStr2 = myStr.trim();  
//==“Earth is a beautiful planet”;

if (myStr2.startsWith(“Earth”)) // returns TRUE

if (myStr2.endsWith(“planet”)) // returns TRUE

if (myStr.startsWith(“Earth”)) 
// returns FALSE due to the leading spaces…

if (myStr.endsWith(“planet”)) 
// returns FALSE due to trailing spaces…

传统方式

function strStartsWith(str, prefix) {
    return str.indexOf(prefix) === 0;
}

function strEndsWith(str, suffix) {
    return str.match(suffix+"$")==suffix;
}

#3楼

拜托,这是正确endsWith实现:

String.prototype.endsWith = function (s) {
  return this.length >= s.length && this.substr(this.length - s.length) == s;
}

如果没有匹配项,使用lastIndexOf只会创建不必要的CPU循环。


#4楼

我不认识你,但是:

var s = "mystring#";
s.length >= 1 && s[s.length - 1] == '#'; // will do the thing!

为什么使用正则表达式? 为什么要弄乱原型? substr? 来...


#5楼

这建立在@charkit接受的答案的基础上,允许将字符串数组或字符串作为参数传入。

if (typeof String.prototype.endsWith === 'undefined') {
    String.prototype.endsWith = function(suffix) {
        if (typeof suffix === 'String') {
            return this.indexOf(suffix, this.length - suffix.length) !== -1;
        }else if(suffix instanceof Array){
            return _.find(suffix, function(value){
                console.log(value, (this.indexOf(value, this.length - value.length) !== -1));
                return this.indexOf(value, this.length - value.length) !== -1;
            }, this);
        }
    };
}

这需要underscorejs-但可能可以进行调整以删除下划线依赖项。


#6楼

if(typeof String.prototype.endsWith !== "function") {
    /**
     * String.prototype.endsWith
     * Check if given string locate at the end of current string
     * @param {string} substring substring to locate in the current string.
     * @param {number=} position end the endsWith check at that position
     * @return {boolean}
     *
     * @edition ECMA-262 6th Edition, 15.5.4.23
     */
    String.prototype.endsWith = function(substring, position) {
        substring = String(substring);

        var subLen = substring.length | 0;

        if( !subLen )return true;//Empty string

        var strLen = this.length;

        if( position === void 0 )position = strLen;
        else position = position | 0;

        if( position < 1 )return false;

        var fromIndex = (strLen < position ? strLen : position) - subLen;

        return (fromIndex >= 0 || subLen === -fromIndex)
            && (
                position === 0
                // if position not at the and of the string, we can optimise search substring
                //  by checking first symbol of substring exists in search position in current string
                || this.charCodeAt(fromIndex) === substring.charCodeAt(0)//fast false
            )
            && this.indexOf(substring, fromIndex) === fromIndex
        ;
    };
}

好处:


#7楼

不要使用正则表达式。 即使使用快速语言,它们也很慢。 只需编写一个检查字符串结尾的函数即可。 这个库有很好的例子: groundjs / util.js。 小心在String.prototype中添加一个函数。 这段代码提供了很好的示例: groundjs / prototype.js通常,这是一个不错的语言级库: groundjs您也可以看看lodash


#8楼

来自developer.mozilla.org String.prototype.endsWith()

摘要

endsWith()方法确定一个字符串是否以另一个字符串的字符结尾,并根据情况返回true或false。

句法

str.endsWith(searchString [, position]);

参量

  • searchString :在此字符串末尾要搜索的字符。

  • position :在此字符串中搜索,就好像该字符串只有这么长; 默认为该字符串的实际长度,限制在该字符串的长度所建立的范围内。

描述

此方法使您可以确定一个字符串是否以另一个字符串结尾。

例子

var str = "To be, or not to be, that is the question.";

alert( str.endsWith("question.") );  // true
alert( str.endsWith("to be") );      // false
alert( str.endsWith("to be", 19) );  // true

技术指标

ECMAScript语言规范第六版(ECMA-262)

浏览器兼容性

浏览器兼容性


#9楼

我刚刚了解了这个字符串库:

http://stringjs.com/

包括js文件,然后使用S变量,如下所示:

S('hi there').endsWith('hi there')

也可以通过安装它在NodeJS中使用它:

npm install string

然后将其作为S变量:

var S = require('string');

如果您不喜欢该网页,则该网页还具有指向其他字符串库的链接。


#10楼

function strEndsWith(str,suffix) {
  var reguex= new RegExp(suffix+'$');

  if (str.match(reguex)!=null)
      return true;

  return false;
}

#11楼

更新(2015年11月24日):

该答案最初发布于2010年(六年前),因此请注意以下有见地的评论:


原始答案:

我知道这是一个老问题了...但是我也需要这个,并且我需要它来跨浏览器工作,所以... 结合每个人的答案和评论并简化一点:

String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
  • 不创建子字符串
  • 使用本机indexOf函数可获得最快的结果
  • 使用indexOf的第二个参数跳过不必要的比较以向前跳过
  • 在Internet Explorer中工作
  • 没有正则表达式并发症

另外,如果您不喜欢在本机数据结构的原型中填充东西,这是一个独立版本:

function endsWith(str, suffix) {
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
}

编辑:正如@hamish在评论中指出的那样,如果您想在安全方面犯错,并检查是否已经提供了实现,则可以只添加typeof检查,如下所示:

if (typeof String.prototype.endsWith !== 'function') {
    String.prototype.endsWith = function(suffix) {
        return this.indexOf(suffix, this.length - suffix.length) !== -1;
    };
}

#12楼

对于咖啡脚本

String::endsWith = (suffix) ->
  -1 != @indexOf suffix, @length - suffix.length

#13楼

对于这么小的问题,有这么多事情,只需使用此正则表达式

 var str = "mystring#"; var regex = /^.*#$/ if (regex.test(str)){ //if it has a trailing '#' } 


#14楼

  1. 不幸的是没有。
  2. if( "mystring#".substr(-1) === "#" ) {}

#15楼

if( ("mystring#").substr(-1,1) == '#' )

- 要么 -

if( ("mystring#").match(/#$/) )

#16楼

所有这些都是非常有用的示例。 添加String.prototype.endsWith = function(str)将帮助我们简单地调用该方法来检查我们的字符串是否以该字符串结尾,那么regexp也可以做到这一点。

我找到了比我更好的解决方案。 感谢大家。


#17楼

此版本避免创建子字符串,并且不使用正则表达式(此处提供一些正则表达式答案;而其他则不适用):

String.prototype.endsWith = function(str)
{
    var lastIndex = this.lastIndexOf(str);
    return (lastIndex !== -1) && (lastIndex + str.length === this.length);
}

如果性能对您很重要,则值得测试lastIndexOf是否实际上比创建子字符串快。 (这可能取决于您使用的JS引擎...)在匹配的情况下,它可能会更快,并且当字符串很小时-但是当字符串很大时,甚至需要回顾整个过程虽然我们并不在乎:(

对于检查单个字符,找到长度然后使用charAt可能是最好的方法。


#18楼

@chakrit可接受的答案是您自己执行此操作的可靠方法。 但是,如果您正在寻找一个打包的解决方案,我建议看看@mlunoe指出的underscore.string 。 使用underscore.string,代码将是:

function endsWithHash(str) {
  return _.str.endsWith(str, '#');
}

#19楼

如果您使用lodash

_.endsWith('abc', 'c'); // true

如果不使用lodash,则可以从其来源中借用。


#20楼

这个问题已经有很多年了。 让我为想要使用投票最多的chakrit答案的用户添加一个重要的更新。

作为ECMAScript 6(实验技术)的一部分,'endsWith'函数已经添加到JavaScript中

在此处引用它: https : //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith

因此,强烈建议添加答案中提到的本机实现是否存在的检查。


#21楼

另一个使用正则表达式的快速替代方法对我来说很有吸引力:

// Would be equivalent to:
// "Hello World!".endsWith("World!")
"Hello World!".match("World!$") != null

#22楼

function check(str)
{
    var lastIndex = str.lastIndexOf('/');
    return (lastIndex != -1) && (lastIndex  == (str.length - 1));
}

#23楼

没有看到slice方法的方法。 所以我就把它留在这里:

function endsWith(str, suffix) {
    return str.slice(-suffix.length) === suffix
}

#24楼

经过漫长的回答,我发现这段代码简单易懂!

function end(str, target) {
  return str.substr(-target.length) == target;
}

#25楼

这是endsWith的实现:

String.prototype.endsWith =函数(str){返回this.length> = str.length && this.substr(this.length-str.length)== str; }


#26楼

这是endsEnd的实现: String.prototype.endsWith = function (str) { return this.length >= str.length && this.substr(this.length - str.length) == str; } String.prototype.endsWith = function (str) { return this.length >= str.length && this.substr(this.length - str.length) == str; }


#27楼

如果您不想使用lasIndexOf或substr,那为什么不只看自然状态的字符串(即数组)

String.prototype.endsWith = function(suffix) {
    if (this[this.length - 1] == suffix) return true;
    return false;
}

或作为独立功能

function strEndsWith(str,suffix) {
    if (str[str.length - 1] == suffix) return true;
    return false;
}

#28楼

return this.lastIndexOf(str) + str.length == this.length;

在原始字符串长度比搜索字符串长度小一且找不到搜索字符串的情况下不起作用:

lastIndexOf返回-1,然后添加搜索字符串的长度,然后剩下原始字符串的长度。

可能的解决方法是

return this.length >= str.length && this.lastIndexOf(str) + str.length == this.length

#29楼

未来检验和/或防止覆盖现有原型的一种方法是进行测试检查,以查看是否已将其添加到String原型中。 这是我对非正则表达式高度评价的版本的看法。

if (typeof String.endsWith !== 'function') {
    String.prototype.endsWith = function (suffix) {
        return this.indexOf(suffix, this.length - suffix.length) !== -1;
    };
}

#30楼

/#$/.test(str)

可以在所有浏览器上运行,不需要猴子打补丁String ,并且不需要扫描整个字符串,就像没有匹配项时lastIndexOf一样。

如果要匹配可能包含正则表达式特殊字符(例如'$'的常量字符串,则可以使用以下命令:

function makeSuffixRegExp(suffix, caseInsensitive) {
  return new RegExp(
      String(suffix).replace(/[$%()*+.?\[\\\]{|}]/g, "\\$&") + "$",
      caseInsensitive ? "i" : "");
}

然后你可以像这样使用它

makeSuffixRegExp("a[complicated]*suffix*").test(str)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JavaScript中的endsWith 的相关文章

随机推荐

  • Docker 安装教程

    目录 一 离线安装 一 CentOS 离线安装 一 下载地址 1 选择系统的型号 选择linux CentOS 2 上传文件到CentOS 服务器 二 开始安装 1 解压压缩包 2 解压得到的文件复制到 usr bin目录下 3 注册doc
  • 想要好看的壁纸图片,用这个网站一键解决,不用爬虫也能实现爬虫效果,一键爬取图片网站所有的图片

    想要好看的壁纸图片 用这个网站一键解决 不用爬虫也能实现爬虫效果 一键爬取图片网站所有的图片 网站的地址 https extract pics 演示例子 图片网站 https www sohu com a 582693827 1211239
  • eclipse创建maven项目报Could not calculate build plan: Plugin org.apache.maven.plugins:maven-war-plugin:2.

    创建maven项目eclipse报下面错误 Could not calculate build plan Plugin org apache maven plugins maven war plugin 2 2 or one of its
  • 宋浩高等数学笔记(十二)无穷级数

    完结 宋浩笔记系列的最后一更 之后会出一些武忠祥老师的错题 笔记总结 10月份就要赶紧做真题了
  • C++多态----虚函数初级剖析

    多态说白了就是多种形态 在C 中不少的函数都可以实现多种形态 例如函数重载 运算符重载等等 这种重载一般都是在编译阶段时就已经确定了形态 这种多态 我们一般称之为静态多态 那么既然静态多态是在编译阶段就已经确定好了形态 那么动态多态 自然也
  • 项目有大量的spring日志,log配置level无效的解决方案

    思路 log配置文件的level无效 是因为启动spring的时候 log尚未加载 解决方案 1 web xml中的log监听器的启动顺序早于spring监听器 2 log配置文件生效后 可根据日志种类设置level进行拦截 参考 web
  • 黑暗精灵修改为国内源

    第1步 修改 etc pacman d mirrorlist vim etc pacman d mirrorlist 1 第2步 修改 etc pacman d blackarch mirrorlist vim etc pacman d b
  • python 安装whl文件

    python 安装whl文件 使用场景 在terminal中 通过 pip install 命令进行第三方模块安装时 由于网络获其他原因会使得第三方模块下载失败 导致安装失败 此时 我们可以先通过下载网址将第三方模块包手动下载到本地 再手动
  • Linux系统下 查找已安装软件的命令

    1 find 使用find查找文件的所在路径 find 查找路径 查找参数 在根目录下查找以 conf结尾的文件 find name conf 2 ps 通过查找进程的方法找到对应的包的路径 ps ef grep mongo 也可以简写成
  • mysql5.7.13+VS3013 源代码阅读调试

    之前写Java 对C make cmake都不是很熟 所以参考了以下这些前辈写的博客 最后成功搭建了mysql5 7 13 VS3013调试环境 自己总结了需要需要注意的几点 Windows VS2012环境下编译调试MySQL源码 一 W
  • SQLServer如果指定列列值相同则用逗号拼接其他指定列数据 stuff函数+for xml path

    for xml path 就是将 sql 查询出来的内容以XML的格式显示出来 Stuff 查询字符串 开始位置 数字 长度 数字 需插入的字符串 示例 55替换abcd123字符串中的a 示例 55替换abcd123字符串中的abcd 示
  • vue+Echarts绘制k线图(二)--分时图和交易量图

    目录 1 前言 2 分时图 2 1 vue引入Echarts 2 2 分时图介绍 2 3 分时折线图配置 2 4 组合交易量图 2 5 鼠标指示数据设置 2 6 项目完整代码 3 总结 1 前言 近来发现Echarts API越发的强大 对
  • 二分查找的各种应用详解(C++)

    基本概念 Binary Search 二分查找也称折半查找 它是一种效率较高的查找方法 使用二分查找要求线性表必须采用顺序存储结构 而且表中元素按关键字有序排列 基本原理 查找 因为序列已经单调且有序排列 从中间位置开始比较 一次可以排除一
  • 只考一门数据结构!安徽工程大学计算机考研

    安徽工程大学 考研难度 内容 23考情概况 拟录取和复试分析 院校概况 23专业目录 23复试详情 各专业考情分析 各科目考情分析 正文992字 预计阅读 3分钟 2023考情概况 安徽工程大学计算机相关各专业复试和拟录取分析 083500
  • 分布式开放消息系统(RocketMQ)的原理与实践

    分布式开放消息系统 RocketMQ 的原理与实践 作者 CHEN川 关注 2016 02 25 15 43 字数 6784 阅读 135462 评论 49 喜欢 351 赞赏 7 一年前为了一次内部分享而写的这篇文章 没想到会有这么多人阅
  • (ANC)前三章思维导图总结

    最近发现对于一本书 如果一点点事无巨细的做笔记 效率会比较低 于是改变了一下之前的读书方式 用思维导图的做读书笔记 这样便于了解整本书的框架和每章的大致内容 也仅限于自己做笔记用
  • 数据结构和算法(栈的模拟、前中后缀表达式、表达式求值步骤和思路)

    1 栈的介绍 栈的英文为 stack 栈是一个先入后出 FILO First In Last Out 的有序列表 栈 stack 是限制线性表中元素的插入和删除只能在线性表的同一端进行的一种特殊线性表 允许插入和删除的一端 为变化的一端 称
  • qt中qwt的安装的方式

    参考大神博客 https blog csdn net imkelt article details 51234230 utm medium distribute pc relevant none task blog BlogCommendF
  • Error in nextTick “TypeError Cannot read property ‘xxx‘ of undefined“

    报这个错主要是因为子组件还没加载完成就对子组件进行赋值 推荐使用第一个 this nextTick gt 修改子组件的内容 或 setTimeout gt 修改子组件的内容 50 父组件传值给子组件 子组件不能直接修改 会报错 子组件修改父
  • JavaScript中的endsWith

    如何在JavaScript中检查字符串是否以特定字符结尾 示例 我有一个字符串 var str mystring 我想知道该字符串是否以 结尾 我该如何检查 JavaScript中是否有endsWith 方法 我有一个解决方案是获取字符串的