0

I have an array and would like to use the same concept as a like in SQL to find certain characters in a string.

This what I'm trying to use:

if (nameArray[i].nameInfo.fullName ^= "Bob") {
   // TODO: some code.
}

Thanks for any help.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
MdeVera
  • 647
  • 5
  • 8
  • 22
  • possible duplicate of [JavaScript: string contains](http://stackoverflow.com/questions/1789945/javascript-string-contains) – i_am_jorf Aug 29 '11 at 16:20

4 Answers4

2

Use String.indexOf().

i_am_jorf
  • 53,608
  • 15
  • 131
  • 222
2
if (nameArray[i].nameInfo.fullName.indexOf("Bob") != -1) {
    //todo : some code.
}
Dennis
  • 32,200
  • 11
  • 64
  • 79
1

Beware that indexOf is not supported by earlier versions of IE. In which case the following code can be included.

if(!Array.indexOf){
        Array.prototype.indexOf = function(obj){
            for(var i=0; i<this.length; i++){
                if(this[i]==obj){
                    return i;
                }
            }
            return -1;
        }
    }

Ps. i was going to post this as a comment but don't have enough reputation to do so yet :-/

aziz punjani
  • 25,586
  • 9
  • 47
  • 56
0

I don't know exactly what you are looking for, but it seems from your code that you want to find a first name. If this was just an example, and you don't want a first name, I probably won't be answering your question well. I couldn't find anything about if(foo ^= bar) online.

It would be easy to get the first word in a string (like a first name) through var firstName = name.split(' ')[0].

To find out how similar a string is to another string, this was suggested in another SO answer. I don't know anything about it.

Personally if given the task of finding if a first name is similar to a string given, I would compare similarity of both strings after string.toLowerCase(), and/or compare each character. The library above seems much better if you are looking for overall similarity, but a custom function would allow much more control over similarity detection.

function checkSimilarity(str, target, tolerance) {
    for(x=0; x < str.length();x++) {
        if(str.split('')[x].toLowerCase() == target.split('')[x].toLowerCase()) {
            similar += 1;
        }
    }
    if(similar => (target.length() * tolerance)) {
        return true;
    }
    else {
        return false;
    }
}

No clue how the function above works, but it's what I thought of. (Tolerance needs to be between 0 and 1)

Community
  • 1
  • 1
Ryan Leonard
  • 997
  • 1
  • 9
  • 26