0

Possible Duplicate:
Regular Expression Pattern With A Variable

function function1() {
    var key = "name";
    var sample = "param.name['key'] = name; param.name[i] = 1000; param.name1[i] = name1;";
    var result = result.replace(/param.<<name>>\[(\d+)\]/g, 'parameter[prefix_$1]');
}

Expected result: parameter['prefix_key'] = name; parameter['prefix_i'] = 1000; I cant add variable key into the replace function in regular expresssion.
Please help how to construct the regular expression in replace

0

1 Answer 1

1

You can make a regex out of a string by making a RegExp object:

var regex = new RegExp("param\\." + name + "\\[(\d+)\\]", "g")
var result = result.replace(regex, 'parameter[prefix_$1]');
Sign up to request clarification or add additional context in comments.

4 Comments

~ function function1() { var key = "name"; var sample = "param.name['key'] = name; param.name[i] = 1000; param.name1[i] = name1;"; var regex = new RegExp("param\." + name + "[(\d+)]", "g") var result = sample.replace(regex, 'parameter[prefix_$1]'); alert(result); //Expected result : parameter['prefix_key'] = name; parameter['prefix_i'] = 1000; // I cant add variable key into hte replace function in regular expresssion. }~ I have update function with your code.
@user1812171: Blender missed some escapes... fixed. Still a duplicate though.
NOt getting proper output
@user1812171: Since I don't know which output you get, I cannot help you much. Still, this question has been asked multiple times. Read those question, make sure you understand the basics of regular expressions and try to make it. Everything you need to know is there, you just have to put the pieces together. edit: The problem is in your original expression. \d+ only matches digits and not e.g. 'key'. Adjust your expression accordingly and it will work. If you are not very familiar with regular expression, I recommend to read regular-expressions.info.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.