如何在JavaScript中检查字符串是否以特定字符结尾?
示例:我有一个字符串
var str = "mystring#";
我想知道该字符串是否以#
结尾。 我该如何检查?
JavaScript中是否有
endsWith()
方法?我有一个解决方案是获取字符串的长度并获取最后一个字符并进行检查。
这是最好的方法还是还有其他方法?
#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
;
};
}
好处:
- 这个版本不仅重复使用indexOf。
- 长弦效果最佳。 这是一个速度测试http://jsperf.com/starts-ends-with/4
- 与ecmascript规范完全兼容。 通过测试
#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
技术指标
浏览器兼容性
#9楼
我刚刚了解了这个字符串库:
包括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年(六年前),因此请注意以下有见地的评论:
Shauna -Google员工的更新-看起来ECMA6添加了此功能。 MDN文章还显示了polyfill。 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
TJ Crowder-在现代浏览器中创建子字符串并不昂贵。 这个答案很可能是在2010年发布的。
this.substr(-suffix.length) === suffix
,简单的this.substr(-suffix.length) === suffix
方法在Chrome上最快,在IE11上与indexOf相同,并且在Firefox上仅慢4%(fergetaboutit领域): jsperf.com/endswith-stackoverflow / 14如果结果为假,则更快,更全面: jsperf.com/endswith-stackoverflow-when-false 当然,当ES6添加endsWith时,这一点就没有意义了。 :-)
原始答案:
我知道这是一个老问题了...但是我也需要这个,并且我需要它来跨浏览器工作,所以... 结合每个人的答案和评论并简化一点:
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楼
- 不幸的是没有。
-
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)