klox
klox

Reputation: 2093

need code for search another character

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

Answers (3)

klox
klox

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

Kobi
Kobi

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 ifs:

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:

  1. D is always after U: if(str.match(/U\w*D$/i))
  2. D is always last: if(str.match(/U\w*D$/i))
  3. D and U are on the same block (any order): 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

Matthew Flaschen
Matthew Flaschen

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

Related Questions