Ravi Chothe Ravi Chothe - 1 year ago 105
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>

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


Answer Source

Use RegExp constructor

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

Demo: Fiddle

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download