how to modify this code if i want search JD from var str="KD-S35JWD"..i try this but doesn’t work:
<script type="text/javascript">
var str = "KD-R435jwd";
var hasUD;
var hasJD;
var hasED;
var hasEED;
var patt1 = str.match(/U/gi);
var patt2 = str.match(/J/gi);
var patt3 = str.match(/E/gi);
var patt4 = str.match(/EE/gi);
var patt5 = str.match(/D/gi);
if (patt1 && patt5) {
hasUD = 'UD';
document.write(hasUD);
} else if (patt2 && patt5 {
hasJD = 'JD';
document.write(hasJD);
} else if (patt3 && patt5) {
hasED = 'ED';
document.write(hasED);
} else {
hasEED = 'EED';
document.write(hasEED);
</script>
Your posted code is correct, besides one points: In JavaScript,
elseifshould beelse if.If it possible that a string has both combination of characters, you may want to remove the
elseand have twoifs:Another option is to use a more specific pattern. Currently you check for the characters anywhere in the string. For example, the
DinKD-is enough to satisfy your condition. Depending on your specification:if(str.match(/U\w*D$/i))if(str.match(/U\w*D$/i))if(str.match(/U\w*D|D\w*U/i))Another option is to use a single match for all cases:
One last note: you don’t need the
/gflag in this case. The global flag is used to find all occurrences of the patters, but here you’re only checking for one.