标题: JavaScript中如何判断字符串以指定子串结尾 https://scz.617.cn/misc/201711061152.txt 写windbg jscript插件时冷不丁碰上这个需求,判断字符串以指定子串结尾。对js编 程不熟,最初自己傻乎乎地实现了一个版本,后来无意中发现有内置endsWith()。此 处列举一些实现,非指导性,仅仅是收藏代码片段。 1) 内置版本 -------------------------------------------------------------------------- if ( a.endsWith( b ) ) -------------------------------------------------------------------------- 2) 我最初的2B版本,用substring()实现,而且用"==",没用"===" -------------------------------------------------------------------------- String.prototype.endsWith = function ( str ) { if ( str == null || str.length > this.length ) { return false; } if ( this.substring( this.length - str.length ) == str ) { return true; } else { return false; } }; if ( a.endsWith( b ) ) -------------------------------------------------------------------------- function PrivateStringEndWith ( a, b ) { if ( b == null || a == null || b.length > a.length ) { return false; } if ( a.substring( a.length - b.length ) == b ) { return true; } else { return false; } } if ( PrivateStringEndWith( a, b ) ) -------------------------------------------------------------------------- 3) 用indexOf()实现 -------------------------------------------------------------------------- String.prototype.endsWith = function ( str ) { return this.indexOf( str, this.length - str.length ) !== -1; }; -------------------------------------------------------------------------- 4) 用substr()实现 -------------------------------------------------------------------------- String.prototype.endsWith = function ( str ) { return this.substr( -str.length ) === str; }; -------------------------------------------------------------------------- 可以多一个预检查,没有内置版本时才自己实现 -------------------------------------------------------------------------- if ( typeof String.prototype.endsWith !== 'function' ) { String.prototype.endsWith = function ( str ) { return this.substr( -str.length ) === str; } }; -------------------------------------------------------------------------- 5) 用正则表达式实现 -------------------------------------------------------------------------- String.prototype.endsWith = function ( str ) { var reg = new RegExp( str+"$" ); return reg.test( this ); }; --------------------------------------------------------------------------