如何检查字符串是否以JavaScript中的特定字符结束?
示例:我有一个字符串
var str = "mystring#";
我想知道字符串是否以#结尾。我怎么检查呢?
在JavaScript中有endsWith()方法吗? 我有一个解决方案,取字符串的长度,并得到最后一个字符,并检查它。
这是最好的办法还是还有别的办法?
如何检查字符串是否以JavaScript中的特定字符结束?
示例:我有一个字符串
var str = "mystring#";
我想知道字符串是否以#结尾。我怎么检查呢?
在JavaScript中有endsWith()方法吗? 我有一个解决方案,取字符串的长度,并得到最后一个字符,并检查它。
这是最好的办法还是还有别的办法?
当前回答
这么多东西,这么小的问题,只是使用这个正则表达式
Var STR = "mystring#"; Var regex = /^.*#$/ 如果(regex.test (str)) { //如果后面有一个'#' }
其他回答
这么多东西,这么小的问题,只是使用这个正则表达式
Var STR = "mystring#"; Var regex = /^.*#$/ 如果(regex.test (str)) { //如果后面有一个'#' }
String.prototype.endsWith()
总结
endsWith()方法确定字符串是否以另一个字符串的字符结束,并根据需要返回true或false。
语法
str.endsWith(searchString [, position]);
参数
searchString: 在此字符串的末尾要搜索的字符。 位置: 在这个字符串中搜索,就好像这个字符串只有这么长;默认为此字符串的实际长度,在此字符串长度建立的范围内。
描述
此方法允许您确定字符串是否以另一个字符串结束。
例子
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
规范
ECMAScript语言规范第六版(ECMA-262)
浏览器兼容性
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(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规范。它通过了测试
if( ("mystring#").substr(-1,1) == '#' )
——或者——
if( ("mystring#").match(/#$/) )