0

I use this code and My question would be if there is a better way to check a string than indexOf:

if(documentFile.ending.indexOf('pdf') > -1 || documentFile.ending.indexOf('PDF') > -1 || documentFile.ending.indexOf('docx') > -1)
3
  • 1
    Yeah you have it in ES6. Or you can use regex to do this if (/pdf/i.test(documentFile.ending)) Commented Jan 12, 2017 at 14:28
  • I was thinking regex as well: /pdf/.test(documentFile.ending) Commented Jan 12, 2017 at 14:29
  • 1
    Please define "better". Better in what? What is wrong with indexOf ? Commented Jan 12, 2017 at 14:33

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

@Orangesandlemons no it doesnt. have you seen the polyfill for String.prototype.includes ?
sorry, got mixed up with string.includes/indexOf and array.includes/indexOf. Removed original comment
0

In ES6 you have better option to use "includes"

otherwise use regex

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

Comments

0

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. :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.