JavaScript中的endsWith
如何在JavaScript中检查字符串是否以特定字符结尾 我有一个字符串JavaScript中的endsWith,javascript,string,ends-with,Javascript,String,Ends With,如何在JavaScript中检查字符串是否以特定字符结尾 我有一个字符串 var str = "mystring#"; 我想知道该字符串是否以#结尾。我怎么检查 JavaScript中是否有endsWith()方法 我的一个解决方案是计算字符串的长度,得到最后一个字符并进行检查 这是最好的办法还是有别的办法 不幸的是没有 if(“mystring#。”.substr(-1)==“#”){} --或-- 所有这些都是非常有用的例子。添加String.prototype.endsWith=func
var str = "mystring#";
我想知道该字符串是否以#
结尾。我怎么检查
endsWith()
方法if(“mystring#。”.substr(-1)==“#”){}
所有这些都是非常有用的例子。添加
String.prototype.endsWith=function(str)
将帮助我们简单地调用该方法来检查字符串是否以它结尾,而regexp也会这样做
我找到了一个比我更好的解决办法。谢谢大家。此版本避免创建子字符串,并且不使用正则表达式(此处的一些正则表达式答案将有效;其他答案无效): 如果性能对您很重要,那么值得测试
lastIndexOf
是否比创建子字符串更快。(这很可能取决于您使用的JS引擎…)在匹配情况下,它可能会更快,当字符串很小时-但当字符串很大时,它需要回顾整个过程,尽管我们并不关心:(
对于检查单个字符,找到长度,然后使用charAt
可能是最好的方法
return this.lastIndexOf(str) + str.length == this.length;
在原始字符串长度比搜索字符串长度小一个且未找到搜索字符串的情况下不起作用:
lastIndexOf返回-1,然后添加搜索字符串长度,剩下的是原始字符串的长度
一个可能的解决办法是
return this.length >= str.length && this.lastIndexOf(str) + str.length == this.length
将在所有浏览器上工作,不需要对字符串进行猴子补丁,也不需要像不匹配时的lastIndexOf
那样扫描整个字符串
如果要匹配可能包含正则表达式特殊字符的常量字符串,如“$”
,则可以使用以下命令:
function makeSuffixRegExp(suffix, caseInsensitive) {
return new RegExp(
String(suffix).replace(/[$%()*+.?\[\\\]{|}]/g, "\\$&") + "$",
caseInsensitive ? "i" : "");
}
然后你可以像这样使用它
makeSuffixRegExp("a[complicated]*suffix*").test(str)
来吧,这是正确的
endsWith
实现:
String.prototype.endsWith = function (s) {
return this.length >= s.length && this.substr(this.length - s.length) == s;
}
使用lastIndexOf
只会在没有匹配的情况下创建不必要的CPU循环。更新(2015年11月24日):
此答案最初发布于2010年(六年前),因此请注意以下有见地的评论:
- -
谷歌的更新-看起来ECMA6增加了这个功能。MDN文章还显示了一个polyfill
- -
在现代浏览器上创建子字符串并不昂贵;这个答案很可能是在2010年发布的。现在,简单的
this.substr(-suffix.length)===suffix
方法在Chrome上速度最快,在IE11上与indexOf相同,而且只慢了4%(FergetaboutitTerritory)在Firefox上:当结果为假时,速度会更快:当然,随着ES6添加了endsWith,这一点是没有意义的。:-
原始答案: 我知道这是一个老问题。。。但我也需要这个,我需要它来跨浏览器工作,所以将每个人的答案和评论结合起来并稍微简化:
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
- 不创建子字符串
- 使用本机
函数获得最快的结果indexOf
- 使用
的第二个参数跳过不必要的比较以向前跳过indexOf
- 在Internet Explorer中工作
- 没有Regex并发症
此外,如果您不喜欢在本机数据结构的原型中填充内容,这里有一个独立的版本:
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;
};
}
如果您不想使用lasIndexOf或substr,那么为什么不直接查看处于自然状态的字符串(即数组) 或者作为一个独立的函数
function strEndsWith(str,suffix) {
if (str[str.length - 1] == suffix) return true;
return false;
}
未来验证和/或防止覆盖现有原型的一种方法是进行测试检查,查看是否已将其添加到字符串原型中。以下是我对非正则表达式高评级版本的看法
if (typeof String.endsWith !== 'function') {
String.prototype.endsWith = function (suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
}
我希望这有帮助
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;
}
我不知道你的情况,但是:
var s = "mystring#";
s.length >= 1 && s[s.length - 1] == '#'; // will do the thing!
为什么是正则表达式?为什么要搞乱原型?替代品?来吧…这建立在@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);
}
};
}
这需要下划线-但可能可以调整以删除下划线依赖项。if(typeof String.prototype.endsWith!=“function”){
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
;
};
}
/**
*String.prototype.endsWith
*检查给定字符串是否位于当前字符串的末尾
*@param{string}substring要在当前字符串中定位的子字符串。
*@param{number=}position在该位置结束endsWith检查
*@return{boolean}
*
*@edition ECMA-262第6版,15.5.4.23
*/
String.prototype.endsWith=函数(子字符串,位置){
子字符串=字符串(子字符串);
var substring=substring.length | 0;
如果(!subLen)返回true;//空字符串
var strLen=此长度;
如果(位置===void 0)位置=strLen;
else位置=位置| 0;
如果(位置<1)返回false;
var fromIndex=(strLen=0 | | subcn====-fromIndex)
&& (
位置===0
//如果位置不在字符串的and处,我们可以优化搜索子字符串
//通过检查子字符串的第一个符号是否存在于当前字符串的搜索位置
||this.charCodeAt(fromIndex)==substring.charCodeAt(0)//fast false
)
if (typeof String.endsWith !== 'function') {
String.prototype.endsWith = function (suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -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)/));
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;
}
var s = "mystring#";
s.length >= 1 && s[s.length - 1] == '#'; // will do the thing!
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);
}
};
}
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
;
};
}
str.endsWith(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
S('hi there').endsWith('hi there')
npm install string
var S = require('string');
function strEndsWith(str,suffix) {
var reguex= new RegExp(suffix+'$');
if (str.match(reguex)!=null)
return true;
return false;
}
String::endsWith = (suffix) ->
-1 != @indexOf suffix, @length - suffix.length
function endsWithHash(str) {
return _.str.endsWith(str, '#');
}
_.endsWith('abc', 'c'); // true
// Would be equivalent to:
// "Hello World!".endsWith("World!")
"Hello World!".match("World!$") != null
function endsWith(str, suffix) {
return str.slice(-suffix.length) === suffix
}
function end(str, target) {
return str.substr(-target.length) == target;
}