[英]Javascript - is there a better way to check an string instead of indexOf
我使用此代码,我的问题是,是否有比indexOf更好的方法来检查字符串:
if(documentFile.ending.indexOf('pdf') > -1 || documentFile.ending.indexOf('PDF') > -1 || documentFile.ending.indexOf('docx') > -1)
ES6具有布尔函数。 采用:
if ( documentFile.ending.includes('pdf') ) { }
或正则表达式:
if ( documentFile.ending.match(/your-regex/) { }
规范示例: https : //developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/String/includes
如果您使用的是ES6,则可能需要查看String.prototype.includes
var str = 'To be, or not to be, that is the question.';
console.log(str.includes('To be')); // true
在ES6中,您可以更好地选择使用“包含”
否则使用正则表达式
if(/pdf/i.test(documentFile.ending))
好吧, indexOf
确实非常快,比使用正则表达式快很多。 但是类似/pdf$/i.test(str)
东西可以让您测试结束以及不区分大小写。 但是您可能会更精确:
function endsWith(str, ending) {
return str != null
&& ending != null
&& ending.length <= str.length
&& str.lastIndexOf(ending) === str.length - ending.length;
}
注意ending.length <= str.length
在那里,所以您不必做endsWith("", "a")
事情就可以得到true
。 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.