views:

61

answers:

6

i have been type some string inside textfield that is "KD-G435MUN2D"... i already use this code for search "UD" character from that string:

<script>
     var str="KD-R435MUN2D";
     var patt1=/UD/gi;
     document.write(str.match(patt1));
</script>

but this code doesn't work..where is my fault?

+1  A: 

That's because UD isn't in your string!

dplass
how to modify that script?that i can search "U" and "D" characters and show result like "UD"...
klox
I don't know what you mean.Maybe you mean: `if (str.matches(/U.*D/)) { document.write("UD"); }`
dplass
i already use meredith L. Patterson answer then modify my answer...it make my result show more specific..
klox
A: 

That will only match U and D together. Try:

var str="KD-R435MUN2D";
var patt1=/[U|D]/gi;
alert(str.match(patt1));

This will return 'U,D,U'

Dale
how if i want show the result like "UD" after search "U" and "D" characters?
klox
Do you have to have 'UD' returned exactly or can you be fine with a Boolean true if it has both a U and a D?
Dale
i think..i'm better use show the result more specific and use /u.*d/g
klox
A: 

I don't see the characters UD consecutively in your test string, and your regex specifies only the substring UD. If you're looking for U[anything]D, you'll need to use /U.*D/gi -- the .* means "zero or more repetitions of any valid character" (not counting newline). This will find UD, if it's there, or in your case, UN2D.

Meredith L. Patterson
i want search "U" and "D" characters..after that i want to show the result as "UD"..how to make that works?
klox
Do you care whether they're immediately consecutive or not? Do you care if the D comes before the U? Your question is vague.
Meredith L. Patterson
may be better i'm use /u.*d/gi because it more specific
klox
A: 

i've try this and it's work...

<script type="text/javascript">

var str="KD-R435MUN2D";
var patt1=/U.*D/g;
document.write(str.match(patt1));

</script>
klox
no, that will return 'UN2D'
Dale
+1  A: 

Try this, it will return 'UD' if it has both a U and a D. Otherwise it will be false.

var str = "KD-R435MUN2D";
var hasUD;
var patt1 = str.match(/U/gi);
var patt2 = str.match(/D/gi);

if (patt1 && patt2) {
    hasUD = 'UD';
} else {
    hasUD = false;
}

document.write(hasUD);
Dale
how to modify that code if var str="KD-S35JwD"; and i want search JD ?
klox
change str.match(/U/gi) to str.match(/J/gi)
Dale
no i mean like this..see my answer
klox
A: 
var str = $(this).val; 
var hasUD; 
var hasJD; 
var patt1 = str.match(/u/gi); 
var patt2 = str.match(/J/gi);
var patt3 = str.match(/D/gi); 

if (patt1 && patt3) { 
        hasUD = 'UD'; 
}elseif (patt2 && patt3) { 
        hasJD = 'JD'; } 
klox
just change 'elseif' to 'else if', with a space.
Dale