1

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.

2
  • 1
    Operating on a HTML string is the wrong solution. 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. Commented Jul 6, 2013 at 11:05

2 Answers 2

9

Please replace

var rep_block = block.replace(replace_str,replace_with);

with

var rep_block = block.split(replace_str).join(replace_with);
Sign up to request clarification or add additional context in comments.

Comments

-1

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);

3 Comments

please check jsFiddle first. var rep_block = block.replace(/replace_str/g,replace_with); // replace nothing
oh, string to replace include brackets... i updated jsfiddle: jsfiddle.net/2QFUw/6 but this is not good solution. Use split + join solution by @Hitesh
Please update your answer anyway to use a properly escaped replace_str. Right now the second part is plain wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.