Someone
Someone

Reputation: 3578

Regex replacing character immediately after matches

The Problem

I'm using Regex to replace all occurrences of the number 1 in a given html() string. However, I don't want it to replace the 1 in 12, for example. I'm doing this to make certain parts of cloning a form easier.

So far, it works. However, it also replaces the character immediately after the match. For example, I'm trying to replace the 1 in name[1] to make it name[2] - however, it ends up as name[2. See the snippet below;

note - odd issue with the snippet. After duplicating the element, the entire thing disappears. Same thing happens on JSfiddle but not locally.

$("form").on("click", ".add-race", function(){
    var row = $(".add-race-row").first(); // use this to clone the section
    var newRow = row.clone();
    newRow.html(newRow.html().replace(/1[^12]/g,"2"));

    console.log("clicked!");

    $(".add-race-row").last().after(newRow);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
  <div class="row add-race-row">
        <div class="col-12">
             <input name="races[1][name]" class="form-control">
        </div>
        <div class="col-12"> 
             <button class="add-race">Add Race</button>
        </div>
  </div>
</form>

Upvotes: 0

Views: 59

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627517

In order to match 1 not followed with 1 or 2 use

.replace(/1(?![12])/g,"2")
           ^^^^^^^^ 

Here,

  • 1 - matches 1
  • (?![12]) - a negative lookahead asserts the location that is not immediately followed with 1 or 2.

See the regex demo.

Upvotes: 2

Zenoo
Zenoo

Reputation: 12880

You can use a positive lookahead instead : 1(?=[^12])

With your initial RegEx, you were replacing the whole match : 1 and whatever was after.

Here, I only check that what's after the 1 isn't a 1 or a 2. I'm not matching it.

$(".add-race").on("click", function() {
  var row = $(".add-race-row").first(); // use this to clone the section
  var newRow = row.clone();
  newRow.html(newRow.html().replace(/1(?=[^12])/g, "2"));

  console.log("clicked!");

  $(".add-race-row").last().after(newRow);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div class="row add-race-row">
  <div class="col-12">
    <input name="races[1][name]" class="form-control">
  </div>
  <div class="col-12">
    <button class="add-race">Add Race</button>
  </div>
</div>

Upvotes: 2

Related Questions