0

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?

1
  • 2
    The code that you have posted will throw a TypeError as jQuery objects do no have replace method. Commented Jun 29, 2016 at 14:57

1 Answer 1

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">

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! Took the '.replace(new RegExp(oldId, "g"), newId)'' part of your code and this did the trick. Many thanks! =)

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.