简体   繁体   中英

Am I using pattern matching correctly here?

I have the following code. Given that the variable u1 can be any of the following:

NBSLoan|Accept|PPI+No|60Months
NBSLoan|Refer|PPI+No|60Months
DeBSLoan|Accept|PPI+No|60Months

Also, the last part 60Months will always be different, can I pattern match using the following JavaScript? Do I need to put in a special character for the pipe | symbol? Or will this not work as I'm trying to match only the first part of a longer string?

<script type="text/javascript">
var u1 = 'NBSLoan|Accept|PPI+No|60Months';

var n_accept = /^NBSLoan|Accept$/;
var n_refer = /^NBSLoan|Refer$/;
var d_accept = /^DeBSLoan|Accept$/;

if (u1.match(n_accept)) {       
var pvnPixel = '<img src="https://url1.com"/>';
document.write(pvnPixel);
}
else if (u1.match(n_refer)) {       
var pvnPixel2 = '<img src="url2.com"/>';
document.write(pvnPixel2);
}
else if (u1.match(d_accept)) {
var pvnPixel3 = '<img src="url3.com"/>';
document.write(pvnPixel3);  
}
</script>

Do I need to put in a special character for the pipe | symbol? Or will this not work as I'm trying to match only the first part of a longer string?

Both.

  • You need to escape the pipe symbol with a backslash to match a literal pipe character. Without the backslash it means alternation .
  • You also need to remove your end of line anchor.

Try this regular expression:

/^NBSLoan\|Accept/

Why don't you first split fields with split('|') :

function dispatch(u) {
  var parts = u.split('|'),
      key = parts[0] + "_" + parts[1];
      disp_table = {
       'NBSLoan_Accept':'url1.com',
       'NBSLoan_Refer':'url2.com',
       'DeBSLoan_Accept':'url3.com'
      },
      url = disp_table[key];


  url && document.write("<img src=\""+url+"\"/>");
}

You want to also remove the $ (it signifies the end of string) or add a .* to capture all the other characters:

To lose the end:

/^NBSLoan\|Accept/

To match and capture the other characters:

/^NBSLoan\|Accept.*$/

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