Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search for substring inside string

I have been typing a string inside a textfield, "KD-G435MUN2D".

I 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>
like image 843
klox Avatar asked Dec 01 '25 04:12

klox


1 Answers

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);
like image 185
UpHelix Avatar answered Dec 02 '25 20:12

UpHelix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!