简体   繁体   中英

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.

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/

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM