如何在JavaScript中检查字符串是否以特定字符结尾?
示例:我有一个字符串
var str = "mystring#";
我想知道该字符串是否以结尾#
。我该如何检查?
endsWith()
JavaScript中是否有方法?我有一个解决方案是获取字符串的长度并获取最后一个字符并进行检查。
这是最好的方法还是还有其他方法?
如何在JavaScript中检查字符串是否以特定字符结尾?
示例:我有一个字符串
var str = "mystring#";
我想知道该字符串是否以结尾#
。我该如何检查?
endsWith()
JavaScript中是否有方法?
我有一个解决方案是获取字符串的长度并获取最后一个字符并进行检查。
这是最好的方法还是还有其他方法?
all of them are very useful examples. Adding String.prototype.endsWith = function(str)
will help us to simply call the method to check if our string ends with it or not, well regexp will also do it.
I found a better solution than mine. Thanks every one.
Do not use regular expressions. They are slow even in fast languages. Just write a function that checks the end of a string. This library has nice examples: groundjs/util.js. Be careful adding a function to String.prototype. This code has nice examples of how to do it: groundjs/prototype.js In general, this is a nice language-level library: groundjs You can also take a look at lodash
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
;
};
}
Benefits:
This is the implementation of endsWith :
String.prototype.endsWith = function (str) {
return this.length >= str.length && this.substr(this.length - str.length) == str;
}
This is the implementation of endsWith :
String.prototype.endsWith = function (str) { return this.length >= str.length && this.substr(this.length - str.length) == str; }
After all those long tally of answers, i found this piece of code simple and easy to understand!
function end(str, target) {
return str.substr(-target.length) == target;
}
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)/));
if you dont want to use lasIndexOf or substr then why not just look at the string in its natural state (ie. an array)
String.prototype.endsWith = function(suffix) {
if (this[this.length - 1] == suffix) return true;
return false;
}
or as a standalone function
function strEndsWith(str,suffix) {
if (str[str.length - 1] == suffix) return true;
return false;
}
function check(str)
{
var lastIndex = str.lastIndexOf('/');
return (lastIndex != -1) && (lastIndex == (str.length - 1));
}
另一个使用正则表达式的快速替代方法对我来说很有吸引力:
// Would be equivalent to:
// "Hello World!".endsWith("World!")
"Hello World!".match("World!$") != null
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;
}
来自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
没有看到slice
方法的配合。所以我就把它留在这里:
function endsWith(str, suffix) {
return str.slice(-suffix.length) === suffix
}
此版本避免创建子字符串,并且不使用正则表达式(此处提供某些正则表达式答案;而其他则不适用):
String.prototype.endsWith = function(str)
{
var lastIndex = this.lastIndexOf(str);
return (lastIndex !== -1) && (lastIndex + str.length === this.length);
}
如果性能对您很重要,那么值得测试一下是否lastIndexOf
实际上比创建子字符串更快。(这可能取决于您使用的JS引擎...)在匹配的情况下,它可能会更快,并且当字符串很小时-但是当字符串很大时,甚至需要回顾整个过程虽然我们并不在乎:(
对于检查单个字符,找到长度然后使用charAt
可能是最好的方法。
if( "mystring#".substr(-1) === "#" ) {}
拜托,这是正确的endsWith
实现:
String.prototype.endsWith = function (s) {
return this.length >= s.length && this.substr(this.length - s.length) == s;
}
lastIndexOf
如果不匹配,使用只会创建不必要的CPU循环。
return this.lastIndexOf(str) + str.length == this.length;
在原始字符串的长度比搜索字符串的长度小一且找不到搜索字符串的情况下不起作用:
lastIndexOf返回-1,然后添加搜索字符串的长度,然后剩下原始字符串的长度。
可能的解决方法是
return this.length >= str.length && this.lastIndexOf(str) + str.length == this.length
For coffeescript