如何检查字符串是否以JavaScript中的特定字符结束?
示例:我有一个字符串
var str = "mystring#";
我想知道字符串是否以#结尾。我怎么检查呢?
在JavaScript中有endsWith()方法吗? 我有一个解决方案,取字符串的长度,并得到最后一个字符,并检查它。
这是最好的办法还是还有别的办法?
如何检查字符串是否以JavaScript中的特定字符结束?
示例:我有一个字符串
var str = "mystring#";
我想知道字符串是否以#结尾。我怎么检查呢?
在JavaScript中有endsWith()方法吗? 我有一个解决方案,取字符串的长度,并得到最后一个字符,并检查它。
这是最好的办法还是还有别的办法?
当前回答
他们都是非常有用的例子。添加string .prototype. endswith = function(str)将帮助我们简单地调用该方法来检查字符串是否以它结尾,regexp也会这样做。
我找到了比我更好的解决办法。谢谢大家。
其他回答
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;
}
这是另一个对我来说很有魅力的快速替代方法,使用正则表达式:
// Would be equivalent to:
// "Hello World!".endsWith("World!")
"Hello World!".match("World!$") != null
if( ("mystring#").substr(-1,1) == '#' )
——或者——
if( ("mystring#").match(/#$/) )
这建立在@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);
}
};
}
这需要下划线-但是可以调整以删除下划线依赖项。
对于coffeescript
String::endsWith = (suffix) ->
-1 != @indexOf suffix, @length - suffix.length