I have a string and some text (name attr) should be replaced with dynamic text. For example
options[team_member][0][name]
will be replaced with options[team_member][1][name]
.
What far i did:
var current = 1;
var block = jQuery('#contents').html();
var replace_str = 'options[team_member]['+(current-1)+']';
var replace_with = 'options[team_member]['+(current)+']';
/* replace only first match */
var rep_block = block.replace(replace_str,replace_with);
/* replace nothing */
// var rep_block = block.replace(/replace_str/g,replace_with);
/* replace nothing */
// var rep_block = block.replace(/(replace_str)/g,replace_with);
alert(rep_block);
Please check full code in jsFiddle
I cannot find the way how can i solve this. Please help me. Thanks in advance.
I have a string and some text (name attr) should be replaced with dynamic text. For example
options[team_member][0][name]
will be replaced with options[team_member][1][name]
.
What far i did:
var current = 1;
var block = jQuery('#contents').html();
var replace_str = 'options[team_member]['+(current-1)+']';
var replace_with = 'options[team_member]['+(current)+']';
/* replace only first match */
var rep_block = block.replace(replace_str,replace_with);
/* replace nothing */
// var rep_block = block.replace(/replace_str/g,replace_with);
/* replace nothing */
// var rep_block = block.replace(/(replace_str)/g,replace_with);
alert(rep_block);
Please check full code in jsFiddle
I cannot find the way how can i solve this. Please help me. Thanks in advance.
Share Improve this question asked Jul 6, 2013 at 10:59 itskawsaritskawsar 1,2421 gold badge19 silver badges30 bronze badges 2- 1 Operating on a HTML string is the wrong solution. – ThiefMaster Commented Jul 6, 2013 at 11:03
- ok. i want to add a html block with some inputs with some dynamic name. How can i make it? Do you like to share your idea please. – itskawsar Commented Jul 6, 2013 at 11:05
2 Answers
Reset to default 9Please replace
var rep_block = block.replace(replace_str,replace_with);
with
var rep_block = block.split(replace_str).join(replace_with);
Use global replace with "g" flag: /reg_ex_here/g or new RegExp(exp, 'g')
var string = 'bla bla bla';
string.replace(/bla/g, 'ok'); // -> ok ok ok
string.replace(new RegExp('bla', 'g'), 'ok'); // -> ok ok ok
In your code:
var replace_str = 'options\\[team_member\\]\\['+(current-1)+'\\]';
rep_block = block.replace(new RegExp(replace_str, 'g'), replace_with);