简体   繁体   中英

Javascript replace with a regex pattern issue

Please consider the following javascript and html below.
When addAnotherAddress() is run the first time, I'm expecting that all of the 1's inside <div class="previous_address1"> will be replaced with 2's and then that html will be appended to <div id="previous_addresses"> but that's not happening when html.replace(pattern, current_address + 1) runs.

What am I doing wrong here?

var current_address = 1; // Used when adding in previous address entries

function addAnotherAddress() {
    var pattern = '/' + current_address + '/g';
    var html = $('.previous_address' + current_address).html();

    html = html.replace(pattern, current_address + 1);

    $('#previous_addresses').append(
        '<div class="previous_address' + (current_address + 1) + '">' + html + '</div>' 
    );
    current_address += 1;
}

<div id="previous_addresses">
    <span class="text_line">
    <u>Previous Addresses for Past 5 Years</u>
    </span>
    <div class="previous_address1">
    <span class="text_line">
        <i>Address 1</i>
    </span>
    <span class="text_line">
        <label for="previous_street1">Street:</label>
        <input type="text" id="previous_street1" />
    </span>
    <span class="text_line">
        <label for="previous_city1">City:</label>
        <input type="text" id="previous_city1" />
    </span>
    <span class="text_line">
        <label for="previous_state1">State:</label>
        <input type="text" id="previous_state1" />
    </span>
    <span class="text_line">
        <label for="previous_zip1">Zip:</label>
        <input type="text" id="previous_zip1" />
    </span>
    <span class="text_line">
        <label for="previous_county1">County:</label>
        <input type="text" id="previous_county1" />
    </span>
    </div>
</div>

您不能直接使用字符串格式的regexp模式,必须对其进行评估:

html = html.replace(new RegExp(current_address, "g"), current_address + 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM