Ravi Chothe Ravi Chothe - 1 month ago 7
jQuery Question

how to set variable value in pattern regex in Jquery

how to set variable value in pattern regx in Jquery.I want to set pattern value dyanamically.Please help me How to set

<!DOCTYPE html>
<html>
<body>

<script language="javascript">
function checkABC(str){
var test="abc";
var pattern = /'test'/gi
if(str.match(pattern)){
alert('matches');
}else{
alert('no match');
}
}
</script>
<input type="button" value="matches" onclick="checkABC('deabcfg')" />

</body>
</html>

Answer

Use RegExp constructor

function checkABC(str) {
    var test = "abc";
    var pattern = new RegExp(test, 'gi');
    if (str.match(pattern)) {
        alert('matches');
    } else {
        alert('no match');
    }
}

Demo: Fiddle