Barrios
Barrios

Reputation: 75

Javascript regular expression difficulty, match string against a name

I'm trying to match a name obtained from server against input provided by a user, the complete name may or may not be known entirely by the user, for example I should be able to match the following:

Name Obtained: Manuel Barrios Pineda
Input given: Manuel P

Right until now I've tried with this code:

var name_obtained = 'Manuel Barrios Pineda';
var re = new RegExp('\b[' + name_obtained + ']+\b');
var input_string = 'Manuel';

if (input_string.match(re)) {
    alert('Match');
} else {
    alert('No Match');
}

Here's an example: jsfiddle example

EDIT 1: It's required to match input like 'Manuel B', 'Manuel P'

Upvotes: 1

Views: 137

Answers (2)

Bergi
Bergi

Reputation: 664195

var name_obtained = 'Manuel Barrios Pineda';
var re = new RegExp('\b[' + name_obtained + ']+\b');

That's not working. Your building a character class to match a single character between word boundaries. The result will be equal to

var re = /\b[adeilnoruBMP]\b/;
input_string.match(name_obtained)

That would never work when the name_obtained is longer than the input_string. Notice that match will try to find the regex in the input_string, not the other way round.

Therefore I'd suggest to use something simple like

var name_obtained = 'Manuel Barrios Pineda';
var input_string = 'Manuel';

if (name_obtained.indexOf(input_string) > -1) {
    alert('Match');
} else {
    alert('No Match');
}

To use your input_string as a regex to search in the obtained name with omitting middle names or end characters, you could do

String.prototype.rescape = function(save) {
    return this.replace(/[{}()[\]\\.?*+^$|=!:~-]/g, "\\$&");
}

var name_obtained = 'Manuel Barrios Pineda';
var input_string = 'Manuel'; // or 'Manuel P', 'Manuel Pineda', 'Manuel B', 'Barrios P', …

var re = new RegExp("\\b"+input_string.rescape().split(/\s+/).join("\\b.+?\\b"));
if (re.test(name_obtained)) {
    alert('Match');
} else {
    alert('No Match');
}

Upvotes: 2

Paul S.
Paul S.

Reputation: 66304

Perhaps you want something like this

var input_given = 'Manuel P'.replace(/[.+*()\[\]]/g, ' ').replace(/\?/g, '.'),
    name_obtained = 'Manuel Barrios Pineda',
    arr = input_given.split(' '), i, ret = true;

for (i = 0; i < arr.length && ret; ++i) // for each word A in input
    if (arr[i]) // skip ""
        ret = new RegExp('\\b' + arr[i]).test(name_obtained);
            // test for word starting A in name
// if test failed, end loop, else test next word

if (ret) alert('Match'); // all words from input in name
else alert('No Match');  // not all words found

Upvotes: 1

Related Questions