Search for substring inside string
I have been typing a string inside a textfield, "KD-G435MUN2D"
.
I开发者_Go百科 already use this code to search for "UD"
substring 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?
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'; }
I've tried this and it appears to work:
<script type="text/javascript">
var str="KD-R435MUN2D";
var patt1=/U.*D/g;
document.write(str.match(patt1));
</script>
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);
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'
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.
精彩评论