我使用此代码,我的问题是,是否有比indexOf更好的方法来检查字符串:
if(documentFile.ending.indexOf('pdf') > -1 || documentFile.ending.indexOf('PDF') > -1 || documentFile.ending.indexOf('docx') > -1)
ES6 has boolean function. Use:
if ( documentFile.ending.includes('pdf') ) { }
Or for regex:
if ( documentFile.ending.match(/your-regex/) { }
Example spec: https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/String/includes
If you are using ES6 then you may want to look at String.prototype.includes
var str = 'To be, or not to be, that is the question.';
console.log(str.includes('To be')); // true
In ES6 you have better option to use "includes"
otherwise use regex
if(/pdf/i.test(documentFile.ending))
Well, indexOf
is really fast, a lot faster than using a regular expression. But something like /pdf$/i.test(str)
lets you test the end as well as giving you case-insensitivity. But you could be more precise:
function endsWith(str, ending) {
return str != null
&& ending != null
&& ending.length <= str.length
&& str.lastIndexOf(ending) === str.length - ending.length;
}
Note the ending.length <= str.length
which is there so that you don't do something like endsWith("", "a")
and get true
. :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.