[英]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.