如何检查字符串是否以JavaScript中的特定字符结束?
示例:我有一个字符串
var str = "mystring#";
我想知道字符串是否以#结尾。我怎么检查呢?
在JavaScript中有endsWith()方法吗? 我有一个解决方案,取字符串的长度,并得到最后一个字符,并检查它。
这是最好的办法还是还有别的办法?
如何检查字符串是否以JavaScript中的特定字符结束?
示例:我有一个字符串
var str = "mystring#";
我想知道字符串是否以#结尾。我怎么检查呢?
在JavaScript中有endsWith()方法吗? 我有一个解决方案,取字符串的长度,并得到最后一个字符,并检查它。
这是最好的办法还是还有别的办法?
当前回答
这建立在@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);
}
};
}
这需要下划线-但是可以调整以删除下划线依赖项。
其他回答
没有看到接近切片法。所以我就把它留在这里:
function endsWith(str, suffix) {
return str.slice(-suffix.length) === suffix
}
对于coffeescript
String::endsWith = (suffix) ->
-1 != @indexOf suffix, @length - suffix.length
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;
}
不幸的是没有。 If ("mystring#".substr(-1) === "#") {}
如果你不想使用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;
}