最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - String replace: multiple replace is not working in JQuery - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 9

Please 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);
发布评论

评论列表(0)

  1. 暂无评论