0

Currently I am doing the following to check if a String exists in an array:

  $('#finance').click(function(){ // Show Finance & OD
                console.log('Finance jobs');
                for(i = 0; i < jobs.length; i ++){
                    if(jobs[i].department === "Finance & OD"){
                        console.log(jobs[i]);
                    }
                }
            });

However, I'd like to just check if a sub string exists and for it to not be case sensitive. So I tried this but It did not work:

$('#finance').click(function(){ // Show Finance & OD
                    console.log('Finance jobs');
                    for(i = 0; i < jobs.length; i ++){
                        if(jobs[i].department.toLowerCase().indexOf("Finance & OD") >= 0){
                            console.log(jobs[i]);
                        }
                    }
                });

I got this error in the console window: Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

I'm wondering how I could fix my code so that rather checking for the entire string, I would check for part of the String say "Finance" for example and that it would not be case sensitive.

1
  • 1
    can you show what does 'jobs' variable contain..? Commented Mar 23, 2015 at 10:29

3 Answers 3

4

Do it like this:

$('#finance').click(function(){ // Show Finance & OD
                    console.log('Finance jobs');
                    for(i = 0; i < jobs.length; i ++){
                        if(jobs[i].department != 'undefined' && jobs[i].department.toLowerCase().indexOf("Finance & OD") >= 0){
                            console.log(jobs[i]);
                        }
                    }
                });

I think the problem is that you loop through some "undefineds" and therefor get an uncatched exception.

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

Comments

1

This is you can check for particular word and also not case-sensitive:

var jobs = ["Finance & OD", "texT"];
for( var i in jobs ) {

    var regex = new RegExp( "Finance", "i" );
    if( jobs[i].match( regex ) ) {
        console.log(jobs[i]);
    }
}

Comments

0

You need to check for undefined. Try this:

if(jobs[i].department != "undefined" && jobs[i].department.toLowerCase().indexOf("Finance & OD") >= 0){
     console.log(jobs[i]);
}

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.