1

I'm trying to create a regex for the following pattern:-

1234,4321;5678,8765;1234,4321;5678,8765;1234,4321;5678,8765;

/[0-9]+,[0-9]+;/g or /\d+,\d+;/g doesn't seem to work in JavaScript.

Output:-

false

function myFunction() {
  var str = "1234,4321;1234,4321;1234,4321;1234,4321;";
  var patt = new RegExp(/[0-9]+,[0-9]+;/g);
  var res = patt.test(str);
  document.getElementById("demo").innerHTML = res;
}

myFunction()
<div id="demo"></div>

3
  • importblogkit.com/2015/07/does-not-work Commented Jan 20, 2017 at 6:23
  • 2
    define "doesn't seem to work" pls. Regex.test returns a boolean indicating if there are matches or not. it doesn't return actual matches. Use String.match() for that Commented Jan 20, 2017 at 6:25
  • Does the pattern always end with ;? Commented Jan 20, 2017 at 6:25

2 Answers 2

1

Your just need one correction. i.e., pass the global flag g as a second parameter to RegExp constructor.

function myFunction() {
var str = "1234,4321;1234,4321;1234,4321;1234,4321;";
var patt = new RegExp(/[0-9]+,[0-9]+;/, 'g');
var res = patt.test(str);
document.getElementById("demo").innerHTML = res;
}
Sign up to request clarification or add additional context in comments.

1 Comment

OP's code is just fine. Sample. global flag is retained
1

Using the RegEx /^([0-9]+:[0-9]+,)*$/ solves the problem. ()star makes sure the pattern matches every time.

function myFunction() {
  var str = "1234,4321;1234,4321;1234,4321;1234,4321;";
  var patt = new RegExp(/^([0-9]+:[0-9]+,)*$/);
  var res = patt.test(str);
  document.getElementById("demo").innerHTML = res;
}

myFunction()
<div id="demo"></div>

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.