Reputation: 3167
I am trying to replace a number globally in my HTML string by regex but it only replaces the number when it's not attached to an attribute.
e.g. I want to replace the number 123 globally. The problem in this example is that only the number in the value has been changed and not the number between the brackets.
var oldId = 123;
var newId = 1234;
<input type="hidden" name="field_name" value="123">
<input type="radio" name="field_name[123]" class="id_123">
$('.settings').replace(/oldId/g, newId);
Current result
<input type="hidden" name="field_name" value="1234"> <-- changed
<input type="radio" name="field_name[123]" class="id_123"> <--- not changed
I guess I need to modify my regex a somehow?
Upvotes: 0
Views: 123
Reputation: 1
You can use .each()
, g
flag at RegExp
to replace .outerHTML
of elements where name
attribute includes "field_name"
var oldId = 123;
var newId = 1234;
$("input[name*=field_name]").each(function(i, el) {
el.outerHTML = el.outerHTML.replace(new RegExp(oldId, "g"), newId)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" name="field_name" value="123">
<input type="radio" name="field_name[123]" class="id_123">
Upvotes: 1