Bob*_*mar 1085 javascript string ends-with
如何检查字符串是否以JavaScript中的特定字符结尾?
示例:我有一个字符串
var str = "mystring#";
Run Code Online (Sandbox Code Playgroud)
我想知道该字符串是否以#
.结尾.我怎么检查呢?
endsWith()
JavaScript中有方法吗?
我有一个解决方案是获取字符串的长度并获取最后一个字符并检查它.
这是最好的方式还是有其他方式?
cha*_*rit 1754
更新(2015年11月24日):
这个答案最初发布于2010年(六年前).所以请注意这些富有洞察力的评论:
Shauna - Google员工更新 - 看起来ECMA6添加了此功能.MDN文章还显示了一种填充物.https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
TJ Crowder - 在现代浏览器上创建子串并不昂贵; 它可能是在2010年这个答案发布时.目前,简单的this.substr(-suffix.length) === suffix
方法在Chrome上最快,在IE11上与indexOf相同,在Firefox上只有4%的速度(fergetaboutit领域):jsperf.com/endswith-stackoverflow/14当结果为假时,整个过程更快:jsperf.com/endswith-stackoverflow-when-false 当然,随着ES6添加endsWith,这一点没有实际意义.:-)
原始答案:
我知道这是一年前的问题...但我也需要这个,我需要它跨浏览器工作所以... 结合每个人的答案和评论并简化它:
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
Run Code Online (Sandbox Code Playgroud)
indexOf
功能以获得最快的结果indexOf
以跳过此外,如果您不喜欢在本机数据结构的原型中填充东西,这里是一个独立版本:
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
Run Code Online (Sandbox Code Playgroud)
编辑:正如@hamish在评论中所指出的,如果你想在安全方面犯错并检查是否已经提供了实现,你可以添加一个typeof
支票,如下所示:
if (typeof String.prototype.endsWith !== 'function') {
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
}
Run Code Online (Sandbox Code Playgroud)
Mik*_*uel 292
/#$/.test(str)
Run Code Online (Sandbox Code Playgroud)
将适用于所有浏览器,不需要猴子修补String
,并且不需要扫描整个字符串,就像lastIndexOf
没有匹配时一样.
如果要匹配可能包含正则表达式特殊字符的常量字符串,例如'$'
,则可以使用以下内容:
function makeSuffixRegExp(suffix, caseInsensitive) {
return new RegExp(
String(suffix).replace(/[$%()*+.?\[\\\]{|}]/g, "\\$&") + "$",
caseInsensitive ? "i" : "");
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样使用它
makeSuffixRegExp("a[complicated]*suffix*").test(str)
Run Code Online (Sandbox Code Playgroud)
Phi*_*ham 89
if( "mystring#".substr(-1) === "#" ) {}
小智 66
来吧,这是正确的endsWith
实现:
String.prototype.endsWith = function (s) {
return this.length >= s.length && this.substr(this.length - s.length) == s;
}
Run Code Online (Sandbox Code Playgroud)
lastIndexOf
如果没有匹配,使用只会创建不必要的CPU循环.
Jon*_*eet 56
这个版本避免了创建子字符串,并且不使用正则表达式(这里的一些正则表达式答案将起作用;其他正则表达式被破坏):
String.prototype.endsWith = function(str)
{
var lastIndex = this.lastIndexOf(str);
return (lastIndex !== -1) && (lastIndex + str.length === this.length);
}
Run Code Online (Sandbox Code Playgroud)
如果性能对您很重要,那么测试是否lastIndexOf
实际上比创建子字符串更快是值得的.(它很可能取决于你正在使用的JS引擎......)在匹配的情况下它可能会更快,当字符串很小时 - 但是当字符串很大时它需要回顾整个事情甚至虽然我们并不在乎:(
要检查单个字符,找到长度然后使用charAt
可能是最好的方法.
Nik*_*rov 25
没有看到slice
方法的apporach .所以我只想把它放在这里:
function endsWith(str, suffix) {
return str.slice(-suffix.length) === suffix
}
Run Code Online (Sandbox Code Playgroud)
小智 17
return this.lastIndexOf(str) + str.length == this.length;
Run Code Online (Sandbox Code Playgroud)
在原始字符串长度比搜索字符串长度小1并且找不到搜索字符串的情况下不起作用:
lastIndexOf返回-1,然后添加搜索字符串长度,并保留原始字符串的长度.
可能的解决方法是
return this.length >= str.length && this.lastIndexOf(str) + str.length == this.length
Run Code Online (Sandbox Code Playgroud)
Ani*_*rni 16
来自developer.mozilla.org String.prototype.endsWith()
该endsWith()
方法确定字符串是否以另一个字符串的字符结尾,并根据需要返回true或false.
str.endsWith(searchString [, position]);
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
duc*_*lip 10
if( ("mystring#").substr(-1,1) == '#' )
Run Code Online (Sandbox Code Playgroud)
- 要么 -
if( ("mystring#").match(/#$/) )
Run Code Online (Sandbox Code Playgroud)
String.prototype.endsWith = function(str)
{return (this.match(str+"$")==str)}
String.prototype.startsWith = function(str)
{return (this.match("^"+str)==str)}
Run Code Online (Sandbox Code Playgroud)
我希望这有帮助
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…
Run Code Online (Sandbox Code Playgroud)
传统的方式
function strStartsWith(str, prefix) {
return str.indexOf(prefix) === 0;
}
function strEndsWith(str, suffix) {
return str.match(suffix+"$")==suffix;
}
Run Code Online (Sandbox Code Playgroud)
小智 7
我不了解你,但是:
var s = "mystring#";
s.length >= 1 && s[s.length - 1] == '#'; // will do the thing!
Run Code Online (Sandbox Code Playgroud)
为什么正则表达式 为什么搞乱原型?SUBSTR?来吧...
如果你正在使用lodash:
_.endsWith('abc', 'c'); // true
Run Code Online (Sandbox Code Playgroud)
如果不使用lodash,您可以从其来源借用.
使用正则表达式的另一个快速替代方案对我来说就像一个魅力:
// Would be equivalent to:
// "Hello World!".endsWith("World!")
"Hello World!".match("World!$") != null
Run Code Online (Sandbox Code Playgroud)
I just learned about this string library:
Include the js file and then use the S
variable like this:
S('hi there').endsWith('hi there')
Run Code Online (Sandbox Code Playgroud)
It can also be used in NodeJS by installing it:
npm install string
Run Code Online (Sandbox Code Playgroud)
Then requiring it as the S
variable:
var S = require('string');
Run Code Online (Sandbox Code Playgroud)
The web page also has links to alternate string libraries, if this one doesn't take your fancy.
归档时间: |
|
查看次数: |
442642 次 |
最近记录: |