如何检查字符串是否以JavaScript中的特定字符结束?
示例:我有一个字符串
var str = "mystring#";
我想知道字符串是否以#结尾。我怎么检查呢?
在JavaScript中有endsWith()方法吗? 我有一个解决方案,取字符串的长度,并得到最后一个字符,并检查它。
这是最好的办法还是还有别的办法?
如何检查字符串是否以JavaScript中的特定字符结束?
示例:我有一个字符串
var str = "mystring#";
我想知道字符串是否以#结尾。我怎么检查呢?
在JavaScript中有endsWith()方法吗? 我有一个解决方案,取字符串的长度,并得到最后一个字符,并检查它。
这是最好的办法还是还有别的办法?
当前回答
function check(str)
{
var lastIndex = str.lastIndexOf('/');
return (lastIndex != -1) && (lastIndex == (str.length - 1));
}
其他回答
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规范。它通过了测试
这个问题已经问了很多年了。让我为想要使用投票最多的查克里特的答案的用户添加一个重要的更新。
'endsWith'函数已经作为ECMAScript 6的一部分添加到JavaScript(实验技术)
参考网址:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
因此,强烈建议添加检查答案中提到的本机实现是否存在。
function strEndsWith(str,suffix) {
var reguex= new RegExp(suffix+'$');
if (str.match(reguex)!=null)
return true;
return false;
}
if( ("mystring#").substr(-1,1) == '#' )
——或者——
if( ("mystring#").match(/#$/) )
不要使用正则表达式。即使在语速快的语言中,它们也很慢。只需编写一个检查字符串结尾的函数。这个库有很好的例子:groundjs/util.js。 在String.prototype中添加函数时要小心。这段代码有如何做到这一点的很好的例子:groundjs/prototype.js 总的来说,这是一个很好的语言级库:groundjs 你也可以看看lodash