1

I am writing js code to get array of elements after splitting using regular expression.

 var data = "ABCXYZ88";
 var regexp = "([A-Z]{3})([A-Z]{3}d{2})";
 console.log(data.split(regexp));

It returns [ 'ABCXYZ88' ]

But I am expecting something like ['ABC','XYZ','88']

Any thoughts?

2
  • That is not a regular expression. Commented Apr 11, 2017 at 12:16
  • 2
    Try data.match(/^([A-Z]{3})([A-Z]{3})(\d{2})$/).slice(1). Is your string format fixed? 2 x 3 uppercase letters and 2 digits? Commented Apr 11, 2017 at 12:17

3 Answers 3

1

I fixed your regex, then matched it against your string and extracted the relevant capturing groups:

var regex = /([A-Z]{3})([A-Z]{3})(\d{2})/g;
var str = 'ABCXYZ88';
let m = regex.exec(str);
if (m !== null) {
   console.log(m.slice(1)); // prints ["ABC", "XYZ", "88"]
}

In your case, I don't think you can split using a regex as you were trying, as there don't seem to be any delimiting characters to match against. For this to work, you'd have to have a string like 'ABC|XYZ|88'; then you could do 'ABC|XYZ|88'.split(/\|/g). (Of course, you wouldn't use a regex for such a simple case.)

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

1 Comment

This is really good Mike. This is what i expecting. But i though we can do this using split. Anyway this is fine.
1
  1. Your regexp is not a RegExp object but a string.
  2. Your capturing groups are not correct.
  3. String.prototype.split() is not the function you need. What split() does:
var myString = 'Hello World. How are you doing?';
var splits = myString.split(' ', 3);

console.log(splits); // ["Hello", "World.", "How"]

What you need:

var data = 'ABCXYZ88';
var regexp = /^([A-Z]{3})([A-Z]{3})(\d{2})$/;
var match = data.match(regexp);
console.log(match.slice(1)); // ["ABC", "XYZ", "88"]

Comments

0

Try this. I hope this is what you are looking for.

      var reg = data.match(/^([A-Z]{3})([A-Z]{3})(\d{2})$/).slice(1);

https://jsfiddle.net/m5pgpkje/1/

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.