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/

4
  • Use /(\[~[-\da-f]{32,36}\])/ Commented May 30, 2018 at 13:14
  • @WiktorStribiżew nope, doesn't work, tried it already, there are still 3, 2, 2 added to the result jsfiddle.net/7z1yxLw5 Commented May 30, 2018 at 13:16
  • I get How ,[~75e0a072-6464-4e00-8229-a3b6b799a673], to ,[~457713c4-a752-4eed-b835-28f7ef74b682], also ,[~57713c4-a752-4eed-b835-28f7ef74b682], you? Commented May 30, 2018 at 13:17
  • ok, sorry, i see, there is a different pattern than what i modified Commented May 30, 2018 at 13:18

1 Answer 1

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>

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

Comments

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.