0

I want to perform string matching using asterisk() wildcard in javascript. If user enters "vv*k" then:

"vivek" should match.

There can be any number of asterisks. I implemented for a simple case where asterisk can be either at the starting,ending or middle position.

function matchString(pattern,columnValue)
{
    if(pattern.indexOf('*')>-1){
        if (pattern[0] == '*')
        {
            return columnValue.endsWith(pattern.substr(1,pattern.length - 1)) ? true:false
        }
        else if (pattern[pattern.length - 1] == '*')
        {
            return columnValue.startsWith(pattern.substr(0,pattern.length  -1)) ? true:false
        }else{
           var stringArray =  pattern.split('*')
           return columnValue.startsWith(stringArray[0]) &&  columnValue.endsWith(stringArray[stringArray.length-1]) ? true:false
        }
    }else{
       return (columnValue.indexOf(pattern)>-1)
    }
    return false;
}

I want to implement it using Regex so that any number of asteriks can be used at any position.

Vivek Sadh
  • 4,230
  • 3
  • 32
  • 49
  • 3
    `"vv*k" -> "vivek"` should match. is that correct? or did you mean `"viv*k"`? – GrafiCode Oct 05 '15 at 12:52
  • 2
    *"I want to implement it using Regex so that any number of asteriks can be used at any position."* If you run into a *specific* problem in the process, post a question about that. This question is far too broad/vague. – T.J. Crowder Oct 05 '15 at 12:54

1 Answers1

0

if you meant "viv*k" -> "vivek", how about:-

function matchString(pattern,columnValue){
    var regex = new RegExp('^' + pattern.replace(/\*/g, '.{1}') + '$');
    return regex.test(columnValue);
}

alert('pattern = "*oo *a*", value = "foo bar", match = ' + matchString('*oo *a*', 'foo bar'));

Edit

Added ^ for start and $ for end

BenG
  • 14,826
  • 5
  • 45
  • 60