Reputation: 2093
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>
Upvotes: 2
Views: 120
Reputation: 2093
<script type="text/javascript">
var str = "KD-R435jwd";
var matches = str.match(/(EE|[EJU])\w*(D)/i);
if(matches){
var firstLetter = matches[1];
var secondLetter = matches[2];
alert(firstLetter + secondLetter);
}
else {
alert(":(");
}
</script>
this the conclusion...
Upvotes: 0
Reputation: 138007
Your posted code is correct, besides one points: In JavaScript, elseif
should be else if
.
If it possible that a string has both combination of characters, you may want to remove the else
and have two if
s:
if (patt1 && patt3) {
hasUD = 'UD';
alert(hasUD);
}
if (patt2 && patt3) {
hasJD = 'JD';
alert(hasJD);
}
Another option is to use a more specific pattern. Currently you check for the characters anywhere in the string. For example, the D
in KD-
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:
var matches = str.match(/([JU])\w*(D)/i);
if(matches){
var firstLetter = matches[1];
var secondLetter = matches[2];
alert(firstLetter + secondLetter);
}
else {
alert(":(");
}
One last note: you don't need the /g
flag in this case. The global flag is used to find all occurrences of the patters, but here you're only checking for one.
Upvotes: 0
Reputation: 284796
If you want them contiguous:
if(str.indexOf("UD") != -1)
{
document.write("UD");
}
if(str.indexOf("JD") != -1)
{
document.write("JD");
}
If anywhere counts:
var dInd = str.indexOf("D");
if(dInd != -1 && str.indexOf("U") != -1)
{
document.write("UD");
}
if(dInd != -1 && str.indexOf("J") != -1)
{
document.write("JD");
}
Upvotes: 1