user2632918
user2632918

Reputation:

using match(), but it didn't work froma string variable

I have the following fiddle:

jsfiddle

The function:

$('#testbutton').on("click", function(){
    test();
});

function test()
{
    var data = [];
    data['article'] = "monablanko";
    data['specialarticle'] = ["blanko", "bbsooel"];

    var tmp = data['specialarticle'].join("|");
    if( data['article'].match( /(tmp)/ ) )
    {
        $('#result').html("I found a match");
    }
    else
    {
        $('#result').html("I didn't found a match");
    }
}

I didn't found a match with this function. Where is my error? The typeof tmp is string when i use

console.log(typeof tmp);

when i write

if( data['article'].match( /(blanko|bbsooel)/ ) )

then i find a match.

Upvotes: 1

Views: 69

Answers (2)

blgt
blgt

Reputation: 8205

You're matching against the string literal "tmp", not against the value contained inside the variable tmp. Try it like this:

 data['article'].match( new RegExp("(" + tmp + ")") )

eg: http://jsfiddle.net/4K8Km/

Upvotes: 4

MarcoL
MarcoL

Reputation: 9989

You need to create a RegExp to match your string before:

$('#testbutton').on("click", function(){
  test();
});

function test(){
  var data = [];
  data['article'] = "monablanko";
  data['specialarticle'] = ["blanko", "bbsooel"];

  var tmp = new RegExp('('+data['specialarticle'].join("|")+')');
  if( data['article'].match( tmp ) )
  {
    $('#result').html("I found a match");
  }
  else
  {
    $('#result').html("I didn't found a match");
  }
}

Just one more tip: if you don't need to collect a match, but just to test if the string has that RegExp I would suggest to use test instead of match:

tmp.test(data['article']);

rather than

data['article'].match(tmp);

Upvotes: 1

Related Questions