简体   繁体   English

Javascript-有更好的方法来检查字符串而不是indexOf

[英]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 has boolean function. ES6具有布尔函数。 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 规范示例: 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 如果您使用的是ES6,则可能需要查看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" 在ES6中,您可以更好地选择使用“包含”

otherwise use regex 否则使用正则表达式

if(/pdf/i.test(documentFile.ending)) 

Well, indexOf is really fast, a lot faster than using a regular expression. 好吧, indexOf确实非常快,比使用正则表达式快很多。 But something like /pdf$/i.test(str) lets you test the end as well as giving you case-insensitivity. 但是类似/pdf$/i.test(str)东西可以让您测试结束以及不区分大小写。 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 . 注意ending.length <= str.length在那里,所以您不必做endsWith("", "a")事情就可以得到true :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM