2

I have the following code:

const regEx = /\[~(\d|-|[a-f]){32,36}\]/;
var str = "How [~75e0a072-6464-4e00-8229-a3b6b799a673] to
[~457713c4-a752-4eed-b835-28f7ef74b682] also [~57713c4-a752-4eed-b835-28f7ef74b682] you?";
var res = str.split(regEx);

And the res is:

How ,3, to ,2, also ,2, you?

I want to have:

How ,[~75e0a072-6464-4e00-8229-a3b6b799a673], to ,[~457713c4-a752-4eed-b835-28f7ef74b682], also ,[~57713c4-a752-4eed-b835-28f7ef74b682], you?

Here is a code snippet https://jsfiddle.net/3k9g117d/

6axter82
  • 569
  • 2
  • 8
  • 19

1 Answers1

1

The issue is a known one, the repeated capturing group only keeps the last matched value in the group memory buffer.

The (\d|-|[a-f]) group should be re-written as [-\da-f], the limiting quantifier should be applied to it, and the capturing parentheses should wrap the whole pattern,

const regEx = /(\[~[-\da-f]{32,36}\])/;

See the JS demo:

// find elements
var banner = $("#banner-message")
var button = $("button")

var res = [];
function myFunction() {

  const regEx = /(\[~[-\da-f]{32,36}\])/;

  var str = "How [~75e0a072-6464-4e00-8229-a3b6b799a673] to [~457713c4-a752-4eed-b835-28f7ef74b682] also [~57713c4-a752-4eed-b835-28f7ef74b682] you?";
  var res = str.split(regEx);
  document.getElementById("demo").innerHTML = res;
}

// handle click and add class
button.on("click", myFunction)

document.getElementById("demo").innerHTML = res;
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="banner-message">
  <p>Hello World</p>
  <button>Test regEx</button>
  <p id="demo"></p>
</div>
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563