简体   繁体   中英

Alternative to using search or indexOf

Related to my question here .

I've got a JavaScript statement as follows:

<script type="text/javascript">
var u1 = '%pu1=!;';

if (u1.search('NBSLoan|Accept') > -1)
{       
var pvnPixel = '<img src="someurl.com"/>';
document.writeln(pvnPixel);
}
if (u1.indexOf('NBSLoan|Refer') > -1)
{       
var pvnPixel2 = '<img src="someurl2.com"/>';
document.writeln(pvnPixel2);
}
if (u1.indexOf('DeBSLoan|Accept') > -1) {
var pvnPixel3 = '<img src="someurl3.com"/>';
document.writeln(pvnPixel3);    
}
</script>

Given that the u1 variable is a macro that may contain any of the following values:

NBSLoan|Accept|PPI+No|48Months
NBSLoan|Refer|PPI+No|48Months
NBSLoan|Accept|PPI+No|48Months
NBSLoan|Refer|PPI+No|48Months

Also bear in mind the last part (48 months) may change, how can I write a JavaScript statement that will only check the first part of the string? ie whether it is "NBSLoan|Accept" etc?

If you put the above statement in a JSFiddle, yes it does work but I assure you (in live) this isn't working so I'm exploring other possibilities of writing this statement. Could I do something like:

if (u1.search(/NBSLoan|Accept/) ? Would this even work properly with pattern matching? At the moment what is happening is that if u1 is equal to NBSLoan|Accept both url1 and url2 are being fired. What am I doing wrong?

Since your parameters are delimited (seperated) by | 's, we can split on the | 's and check the bits between them, like this:

var u1 = '%pu1=!;';
var u1Split = u1.split("|");

if (u1Split[1] == "Accept") {
    var pvnPixel = '<img src="someurl.com"/>';
    document.writeln(pvnPixel);
} else if (u1Split[1]  == "Refer") {
    var pvnPixel2 = '<img src="someurl2.com"/>';
    document.writeln(pvnPixel2);
} else if (u1Split  == "Accept" && u1Split[0] == "DeBSLoan") {
    var pvnPixel3 = '<img src="someurl3.com"/>';
    document.writeln(pvnPixel3);
}

Let me know if that does the trick. Also, writeln isn't a standard function of document so if you haven't declared it previously somewhere, that would be another issue.

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