The King is The King is - 1 year ago 64
Javascript Question

Searching for similar value in a javascript string

I have a javascript script string that looks like this

var name = "John Peter James";

Now I also have an input field

<input type="text" id="searchForNames" />

Let's assume that a user types this value in the input field

var inputVal = "Pe Jame";

And "Pe" is the begin of "Peter" and "Jame" is also the beginning of "James"

I want to search every word in the string
if it begins with each word in the input value, something like this

inputValue = "Pe Jame"; //returns true
inputValue = "Pes James"; // returns false
inputValue = "John"; //returns true
inputValue = "Joh Pete Ja"; //returns true
inputValue = "Jon Peter James"; // returns false
inputValue = "John John"//returns false

Answer Source

Use this

newInputValue = inputValue.split(' ');
newName = name.split(' ');
for(var i = 0; i < newInputValue.length; i++){
    newValue = newInputValue[i];
    for(var x = 0; x < newName.length; x++){
        eachName = newName[x];
            return true;
            return false;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download